using UnityEngine;

public class Singleton<T> : MonoBehaviour where T : MonoBehaviour
{
	protected static T m_instance; 
	static bool m_canLazyInstantiate = true;
		
	protected void SetSingleton(bool allowLazyInstantiate = false)
	{
		if ( m_instance == null )
			m_instance = gameObject.GetComponent<T>();
		m_canLazyInstantiate = allowLazyInstantiate;
	}
	
	/**
      Returns the instance of this singleton.
    */
	public static T Get 
	{
		get
		{
			if (m_instance == null && m_canLazyInstantiate)
			{
				m_instance = (T)FindObjectOfType(typeof(T));
				if (m_instance == null) 
				{
					GameObject container = new GameObject();
					container.name = typeof(T).ToString();
					m_instance = (T)container.AddComponent(typeof(T));
				}					
			
			}
			
			return m_instance;
		}		
	}
	public static T Instance
	{
		get
		{
			if (m_instance == null && m_canLazyInstantiate)
			{
				m_instance = (T)FindObjectOfType(typeof(T));
				if (m_instance == null) 
				{ 
					GameObject container = new GameObject();
					container.name = typeof(T).ToString();
					m_instance = (T)container.AddComponent(typeof(T));
				}					
			
			}
			
			return m_instance;
		}
	}
	
	public static bool HasInstance() { return m_instance != null; }
}