Unity中常用的两种单例

1、继承class的单例

public class Singleton where T : class
{
    private static T _instance;
    private static readonly object _instanceLock = new object();
    
    public static T Instance
    {
       lock(_instanceLock)
       {
           if(_instance == null)
           {
                //通过T的公共或非公共默认构造函数创建实例
                _instance = (T)Activator.CreateInstance(typeof(T),true);
           }
       }
        return _instance;
    }
}

2、继承Monobehavior的单例

public class MonoSingletonBase : MonoBehaviour
{
    private static T _instance;
    private static object _singletonLock = new object();
    
    public static T Instance
    {
        get
        {
            lock(_singletonLock)
            {
                if(_instance == null)
                {
                    var instances = FindObjectsOfType(typeof(T)) as T[];
                    if(instances != null && instances.Length > 0)
                    {
                        _instance = instances[0];
                    }else
                    {
                        var tempObj = new GameObject(typeof(T).ToString());
                        tempObj.hideFlags = hideFlags.HideInHierarchy;
                        _instance = tempObj.AddComponent();
                        _instance.Init();
                    }
                }
            }
        }
    }
    //初始化
    protected virtual void Init(){}
}

wiki上的继承Monobehavior的单例:http://wiki.unity3d.com/index...

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