using UnityEngine;

// Abstract singleton class to inherit various managers from.
public abstract class Singleton<T> : MonoBehaviour where T : Singleton<T>
{
	static T instance;

	// Whether or not this object should persist when loading new scenes.
	// This should be set in the child classes Init() method.
	public bool persistent = false;

	public static T Instance
	{
		get
		{
			// This would only EVER be null if some other MonoBehavior requests the instance
			// in its' Awake method.
			if (instance == null)
			{
				instance = FindObjectOfType(typeof(T)) as T;
				// This should only occur if 'T' hasn't been attached to any game
				// objects in the scene.
				if (instance == null)
				{
					return null;
				}
				instance.Init();
			}
			return instance;
		}
	}

	// This will initialize our instance, if it hasn't already been prompted to do so by
	// another MonoBehavior's Awake() requesting it first.
	void Awake()
	{
		if (instance == null)
		{
			instance = this as T;
			instance.Init();
			if (persistent)
				DontDestroyOnLoad(gameObject);
		}
		else if(instance != this)
		{
			Destroy(gameObject);
		}
	}

	// Override this in child classes rather than Awake().
	virtual protected void Init() { }

	// Make sure no "ghost" objects are left behind when applicaton quits.
	void OnApplicationQuit()
	{
		instance = null;
	}
}