Loot/LootSpawner.Runtime.cs

A runtime component for a map LootSpawner. It decides whether to spawn loot based on host authority, player count and a random chance, then creates either a LootContainer or a Loot item and stores the spawned GameObject for later deletion.

Networking
using System.Linq;
using Sandbox;

namespace BrickJam;

/// <summary>
/// Runtime behaviour for the <see cref="LootSpawner"/> map component (the stub lives in
/// <c>LegacyMapEntities.cs</c>). Scene-System port of the legacy <c>LootSpawner.SpawnLoot/DeleteLoot</c>.
/// </summary>
public sealed partial class LootSpawner
{
	/// <summary>The object spawned by this spawner, if any (host-side bookkeeping).</summary>
	public GameObject Spawned { get; private set; }

	public void SpawnLoot()
	{
		if ( !Networking.IsHost )
			return;

		var playerCount = Connection.All.Count;
		var chance = MansionGame.Random.NextSingle();

		if ( chance > ChanceToSpawn * playerCount * 0.25f )
			return;

		if ( IsContainer )
		{
			Spawned = LootContainer.Create( WorldPosition, WorldRotation )?.GameObject;
			return;
		}

		if ( LootToSpawn is null )
			return;

		Spawned = Loot.Create( LootToSpawn, WorldPosition, WorldRotation )?.GameObject;

		if ( Spawned is null )
			Log.Error( $"{GameObject.Name} couldn't spawn item! item: {LootToSpawn}" );
	}

	public void DeleteLoot()
	{
		if ( Spawned.IsValid() )
			Spawned.Destroy();

		Spawned = null;
	}
}