私のフレームワーク - Unity3d 用のシングルトン テンプレート

初め

using UnityEngine;

public class Singleton<T> : 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<T> ();
                        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<T> : MonoBehaviour where T : Singleton<T>
    {
        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<T>();
                }

                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;
        }

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

        /// <summary>
        /// 释放
        /// </summary>
        protected virtual void OnRelease()
        {
            
        }
    }
}

 

Supongo que te gusta

Origin blog.csdn.net/zhangchong5522/article/details/118409433
Recomendado
Clasificación