Unity_C#_单例模式

C#_单例模式

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

//继承自Monobehaviour类单例
public class SingletonMono<T> : MonoBehaviour where T : MonoBehaviour
{
    private static object m_Lock = new object();

    private static T m_Instance;
    public static T Instance
    {
        get
        {
            if (m_Instance == null)
            {
                //避免多线程时同时调用
                lock (m_Lock)
                {
                    if (m_Instance == null)
                    {
                        m_Instance = GameObject.FindObjectOfType<T>();
                        if(m_Instance == null)
                        {
                            GameObject go = new GameObject();
                            m_Instance = go.AddComponent<T>();
                            go.name = typeof(T).ToString();
                            DontDestroyOnLoad(go);
                        }
                    }
                }
            }
            return m_Instance;
        }
    }
}


//纯类单例
public class Singleton<T> where T : class, new()
{
    private static object m_Lock = new object();

    private static T m_Instance;
    public static T Instance
    {
        get
        {
            if (m_Instance == null)
            {
                //避免多线程时同时调用
                lock (m_Lock)
                {
                    if (m_Instance == null)
                    {
                        m_Instance = new T();
                    }
                }
            }
            return m_Instance;
        }
    }
}

相关文章

实现Unity AssetBundle资源加载管理器 AssetBundle是实现资源...
Unity3D 使用LineRenderer绘制尾迹与虚线 1.添加LineRendere...
Unity 添加新建Lua脚本选项 最近学习Unity的XLua热更新框架的...
挂载脚本时文件名和类名的关联方式 写过Unity脚本的人应该都...
Unity单例基类的实现方式 游戏开发的过程中我们经常会将各种...
这篇文章主要介绍了Unity游戏开发中外观模式是什么意思,具有...