我的框架-Unity3d的单例模板

第一个

using UnityEngine;

public class Singleton : MonoBehaviour where T : MonoBehaviour
{
    private static T _instance;

    private static object _lock = new object ();

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

            lock (_lock) {
                if (_instance == null) {
                    _instance = (T)FindObjectOfType (typeof(T));

                    if (FindObjectsOfType (typeof(T)).Length > 1) {
                        return _instance;
                    }

                    if (_instance == null) {
                        GameObject singleton = new GameObject ();
                        _instance = singleton.AddComponent ();
                        singleton.name = "(singleton) " + typeof(T).ToString ();

                        DontDestroyOnLoad (singleton);
                    }
                }

                return _instance;
            }
        }
    }

    private static bool applicationIsQuitting = false;

    public void OnDestroy ()
    {
        applicationIsQuitting = true;
    }
}

 第二个

using System;
using UnityEngine;
using System.Collections;

namespace Celf
{
    public class Singleton : MonoBehaviour where T : Singleton
    {
        private static T mInstance;
        private static bool isQuiting;

        public static T Instance
        {
            get
            {
                if (mInstance == null && !isQuiting)
                {
                    mInstance = new GameObject("(Singleton) " + typeof (T).Name).AddComponent();
                }

                return mInstance;
            }
        }

        public static bool isValid() {
            return mInstance != null;
        }

        private void Awake()
        {
            T instance = this as T;

            if (mInstance != null && mInstance != instance)
            {
                DestroyImmediate(this.gameObject);
                return;
            }

            // 切换场景不要销毁GameObject
            DontDestroyOnLoad(gameObject);
            mInstance = instance;
            OnInit();
        }

        private void OnDestroy()
        {
            OnRelease();
            mInstance = null;
        }

        private void OnApplicationQuit()
        {
            isQuiting = true;
        }

        /// 
        /// 初始化
        /// 
        protected virtual void OnInit()
        {
            
        }

        /// 
        /// 释放
        /// 
        protected virtual void OnRelease()
        {
            
        }
    }
}

 

你可能感兴趣的:(我的框架,unity3d)