Unity框架_常见的单例写法

C#中的单例写法 不继承MonoBehaviour 不受到脚本生命周明的影响 手动new出对象

public class Singleton<T> where T : new()
{
    private static T instance;
    public static T Instance
    {
        get
        {
            if (instance == null)
                instance = new T();
            return instance;
        }
    }
}

继承MonoBehaviour 通过Awake完成实例 但在场景中需要手动创建对象并挂载脚本

public class SingletonMono<T> : MonoBehaviour where T : MonoBehaviour
{
    private static T instance;
    public static T GetInstance
    {
        get
        {
            //继承了Mono的脚本 不能够直接new
            return instance;
        }
    }

    protected virtual void Awake()
    {
        instance = this as T;
    }

}

全自动创建 只需继承 终身使用

public class SingletonAutoMono<T> : MonoBehaviour where T : MonoBehaviour
{
    private static T instance;

    public static T Instance
    {
        get
        {
            if (instance == null)
            {
                GameObject obj = new GameObject();
                obj.name = typeof(T).ToString();

                //让这个单例模式对象过场景不移除 因为单例模式对象往往是存在整个程序生命周期中的
                DontDestroyOnLoad(obj);
                instance = obj.AddComponent<T>();
            }
            return instance;
        }
    }

}

猜你喜欢

转载自blog.csdn.net/m0_69778537/article/details/132191346