using UnityEngine;

public abstract class SceneSingleton<T> : MonoBehaviour where T : SceneSingleton<T>
{
	private static T sInstance = null;
	private static object _lock = new object();
	private bool m_bIsObjectDestroyed = false;
	
	public static T Instance
	{
		get
		{
			lock (_lock)
			{
				
				// Instance required for the first time, we look for it
				if (sInstance == null)
				{
					sInstance = GameObject.FindObjectOfType(typeof(T)) as T;
					
					// Object not found, kick off!
					if (sInstance == null)
					{
						Debug.LogError("An instance of " + typeof(T) + " is should be present in the scene!");
					}
				}
				return sInstance;
			}
		}
	}
	
	protected void OnDestroy()
	{
		if (!m_bIsObjectDestroyed)
		{
			m_bIsObjectDestroyed = true;
			Debug.Log("[SceneSingleton] " + typeof(T).ToString() + ".OnDestroy()");
			OnSceneSingletonDestroyed();
		}
	}
	
	protected virtual void OnSceneSingletonDestroyed()
	{
		
	}
}
