欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Unity 小记 —— 泛型单例

程序员文章站 2022-04-03 15:36:24
...

简单泛型单例

/// <summary>
/// 单例基类
/// </summary>
/// <typeparam name="T"></typeparam>
public class Singleton<T> : MonoBehaviour where T : Component
{
    private static bool appQuiting = false;
    private static T instance = null;
    public static T Instance
    {
        get {
            if (instance == null && !appQuiting)
            {
                var obj = GameObject.Find("Singleton Manager");
                if (obj == null)
                {
                    obj = new GameObject("Singleton Manager");
                    DontDestroyOnLoad(obj);
                }
                instance = obj.GetComponent<T>();
                if (instance == null)
                {
                    instance = obj.AddComponent<T>();
                    (instance as Singleton<T>).Init();
                }
            }
            return instance;
        }
        set => instance = value;
    }
    /// <summary>
    /// 初始化函数
    /// </summary>
    protected virtual void Init() { }
    
    private void OnApplicationQuit()
    {
        appQuiting = true;
    }
}

用例:

public class Test01 : MonoBehaviour
{
    private void Start()
    {
        MyClass.Instance.SetName("(⊙_⊙)?");
    }
}
public class MyClass : Singleton<MyClass>
{
    public string Name { get; set; }
    public void SetName(string name)
    {
        Name = name;
    }
}