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;
}
}
上一篇: 有关比较类的文章推荐10篇