Utils/SingletonComponent.cs

Generic singleton Component base class for s&box game code. It stores a static Instance of the derived type, sets it on awake if the component is active, clears it on destroy, and participates in hotload management by saving/restoring whether this instance was active across hotloads.


public abstract class SingletonComponent<T> : Component, IHotloadManaged
	where T : SingletonComponent<T>
{
	public static T Instance { get; private set; }

	protected override void OnAwake()
	{
		if (Active)
		{
			Instance = (T)this;
		}
	}

	void IHotloadManaged.Destroyed(Dictionary<string, object> state)
	{
		state["IsActive"] = Instance == this;
	}

	void IHotloadManaged.Created(IReadOnlyDictionary<string, object> state)
	{
		if (state.GetValueOrDefault("IsActive") is true)
		{
			Instance = (T)this;
		}
	}

	protected override void OnDestroy()
	{
		if (Instance == this)
		{
			Instance = null;
		}
	}
}