Unity比较好用的单例模式

来源:互联网 发布:刷关注软件 编辑:程序博客网 时间:2024/04/28 10:47
// 在网上找的,吧啦吧啦改改,造福Unity程序员
using UnityEngine;public class SingletonMono<T> : MonoBehaviour where T : MonoBehaviour{    private static T _instance;    private static object _lock = new object();    public static T Instance    {        get        {            if (_instance == null)  // null才lock            {                lock (_lock)                {                    if (_instance == null)                    {                        _instance = (T)FindObjectOfType(typeof(T));                        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;    /// <summary>    /// 编辑器模式下可能会在OnDestory后再生成一个    /// </summary>    public void OnDestroy()    {        applicationIsQuitting = true;    }}

0 0