Mrzsc-zhao
10/11/2019 - 7:10 AM

Unity中泛型单例类 (包含是否Destory字段)

Unity中泛型单例类 (包含是否Destory字段)

using UnityEngine;

namespace zsc.Common
{
    public class Singleton<T> : MonoBehaviour where T : Singleton<T>
    {
        protected static T instance;

        public static T Instance
        {
            get
            {
                if (!IsInitialized)
                {
                    var temp = new GameObject("[Singleton]" + typeof(T).Name);
                    temp.AddComponent<T>();
                }

                return instance;
            }
        }

        public static bool IsInitialized
        {
            get { return instance != null; }
        }

        [SerializeField] protected bool dontDestory = false;

        public bool DontDestory
        {
            get => dontDestory;
            set => dontDestory = value;
        }

        protected virtual void Awake()
        {
            if (instance != null)
            {
                Debug.LogWarningFormat("Trying to instantiate a second instance of singleton class {0}",
                    GetType().Name);
                enabled = false;
            }
            else
            {
                instance = (T) this;
            }

            if (dontDestory)
            {
                DontDestroyOnLoad(gameObject);
            }
        }

        protected void OnDestroy()
        {
            if (instance == this)
                instance = null;
        }
    }
}