unity3d:单例模式

C#单例模式

    /// <summary>
    /// C#单例模式
    /// </summary>
    public abstract class Singleton<T> where T : class,new()
    {
        private static T instance;
        private static object syncRoot = new Object();
        public static T Instance
        {
            get
            {
                if (instance == null)
                {
                    lock (syncRoot)
                    {
                        if (instance == null)
                            instance = new T();
                    }
                }
                return instance;
            }
        }

        protected Singleton()
        {
            Init();
        }

        public virtual void Init() { }
    }

MonoBehaviour单例

   public class SingletonMono<T> : MonoBehaviour where T : MonoBehaviour
    {
        private static T _instance;
        private static object _lock = new object();

        public static T Instance
        {
            get
            {
                if (applicationIsQuitting)
                {
                    Debug.LogWarning("[Singleton] Instance '" + typeof(T) +
                        "' already destroyed on application quit." +
                        " Won't create again - returning null.");
                    return null;
                }

                lock (_lock)
                {
                    if (_instance == null)
                    {
                        GameObject singleton = new GameObject();
                        _instance = singleton.AddComponent<T>();
                        singleton.name = string.Format("(singleton) {0}", typeof(T));

                        DontDestroyOnLoad(singleton);
                    }

                    return _instance;
                }
            }
            set
            {
                if (_instance != null)
                {
                    Destroy(value);
                    return;
                }
                _instance = value;
                DontDestroyOnLoad(_instance);
            }
        }

        public static bool applicationIsQuitting = false;


        /// <summary>  
        /// When Unity quits, it destroys objects in a random order.  
        /// In principle, a Singleton is only destroyed when application quits.  
        /// If any script calls Instance after it have been destroyed,  
        ///   it will create a buggy ghost object that will stay on the Editor scene  
        ///   even after stopping playing the Application. Really bad!  
        /// So, this was made to be sure we're not creating that buggy ghost object.  
        /// </summary>  
        public virtual void OnDestroy()
        {
            applicationIsQuitting = true;
        }
    }

猜你喜欢

转载自blog.csdn.net/luoyikun/article/details/80557474