using UnityEngine;

public class Singleton<T> : MonoBehaviour where T : Singleton<T>
{
    public static bool HasInstance { get { return _RawInstance; } }
    public static T _RawInstance;
    public static T I
    {
        get
        {
            if (_RawInstance)
                return _RawInstance;

            T[] managers = FindObjectsOfType<T>();

            if (managers.Length == 0)
            {
                Debug.LogWarning("Singleton<" + typeof(T).FullName + "> has no instance: Initializing new GameObject");

                GameObject obj = new GameObject(typeof(T).FullName);

                try { _RawInstance = obj.AddComponent<T>(); }
                catch
                {
                    Debug.LogError("Singleton<" + typeof(T).FullName + "> has no instance: Failed initializing new GameObject");
                    if (obj) Destroy(obj);
                }

                if (!_RawInstance)
                    Debug.LogError("Singleton<" + typeof(T).FullName + "> has no instance: All instance search and generation attempts failed");

                return _RawInstance;
            }

            if (managers.Length > 1)
                Debug.LogWarning("Singleton<" + typeof(T).FullName + "> has " + managers.Length + " instances: Choosing index 0");

            I = managers[0];
            return I;
        }
        set
        {
            if (_RawInstance != value && value)
                value.OnInstance();
            _RawInstance = value;
        }
    }

    protected virtual void OnInstance() { }
}
