C#单例模式-Unity3D实现继承MonoBehaviour单例

使用时继承该单例类,不用管什么多线程之类的问题,也不用担心性能问题,因为在最开始的时候不管你要不要这个实例,都会被创建出来,所以只是在程序开始的时候消耗时间,到程序结束前不会销毁。

第一个是不继承MonoBehaviour

public class SingletonNull where T : new()
{
    private static T m_instance = default(T);
    protected SingletonNull() { }
    public static T Instance
    {
        get
        {
            if (m_instance == null)
            {
                m_instance = new T();
            }
            return m_instance;
        }
    }
}

第二个是继承MonoBehaviour

using UnityEngine;
public class SingletonMono : MonoBehaviour where T : SingletonMono
{
    private static T m_instance = default(T);
    public static T Instance
    {
        get
        {
            if (m_instance == null)
            {
                GameObject go = null;
                if (GameObject.Find("SingletonMono") == false)
                {
                    go = new GameObject("SingletonMono");
                }
                if(go!=null)
                    m_instance = go.AddComponent();
            }
            return m_instance;
        }
    }
}

 

你可能感兴趣的:(设计模式)