Unity单例模式

 一、继承Mono的单例:

优点:保证一个场景中只存在一个实例。

缺点:第一次访问单例会遍历场景中所有物体,执行效力低。

using UnityEngine;

/// <summary>
/// 继承自MonoBehavour的单例
/// </summary>
public abstract class LY_SingletonMono<T> : MonoBehaviour where T : LY_SingletonMono<T>
{ 
    protected static T instance;
    public static T Instance
    {
        get
        {
            if (instance == null)
            {
                T[] instances = FindObjectsOfType<T>();
                if (instances.Length > 0)
                {
                    instance = instances[0];
                    for (var i = 1; i < instances.Length; i++)
                    {
                        Destroy(instances[i]);
                    }
                }
                else
                {
                    GameObject go = new GameObject("Singleton Of " + typeof(T).Name);
                    instance = go.AddComponent<T>();
                }
            }
            return instance;
        }
    }
    protected virtual void Awake()
    {
        Initialize();
    }
    protected virtual void Initialize() { }
}

猜你喜欢

转载自blog.csdn.net/weixin_40769819/article/details/85218403