using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class MonoSingleton<T> : MonoBehaviour where T : MonoSingleton<T>
{
    private static T instance;
    public static T Instance
    {
        get
        {
            if (instance == null)
            {
                Object[] objs = GameObject.FindObjectsOfType<T>();
                if (objs.Length > 1)
                {
                    Debug.LogError("不能存在两个相同单例类:" + typeof(T).ToString());
                    return null;
                }
                if (objs.Length == 1)
                {
                    instance = ((MonoBehaviour) objs[0]).GetComponent<T>();
                    return instance;
                }
                GameObject obj = new GameObject(typeof(T).ToString());
                instance = obj.AddComponent<T>();
                return instance;
            }
            return instance;

        }
    }

    public virtual void Awake()
    {
        instance = (T) this;
    }
}
