using UnityEngine;

public class Singleton<T> : MonoBehaviour where T : MonoBehaviour
{

    private static T _Instance                  = null;
    private static bool _bApplicationIsQuitting = false;

    public static T Instance
    {
        get
        {
            if (_bApplicationIsQuitting)
            {
                return null;
            }

            if (_Instance == null)
            {
                System.Type type = typeof(T);

                _Instance = (T)GameObject.FindObjectOfType( type );

                if (_Instance == null)
                {
                    GameObject singleton = new GameObject();
                    _Instance = singleton.AddComponent<T>();
                    singleton.name = type.ToString();

                    DontDestroyOnLoad(singleton);
                }
            }

            return _Instance;
        }
    }

    public void Awake()
    {
        if (_Instance == null)
        {
            _Instance = this as T;
            DontDestroyOnLoad(this);
        }
        else
        {
            if (this != _Instance)
            {
                Destroy(this.gameObject);
            }
        }
    }

    public void OnDestroy()
    {
        _bApplicationIsQuitting = true;
    }

}