218 字
1 分钟
游戏设计模式02——泛型单例模式

继承 Mono 泛型单例#

继承 MonoBehaviour 的泛型单例父类,沿用了饿汉单例模式的思路:在 Awake 里登记自己,同时防止重复实例,并且可以选择是否跨场景保留。

using UnityEngine;
public class SingletonMono<T> : MonoBehaviour where T : SingletonMono<T>
{
public static T Instance { get; private set; }
// 子类可重写:是否跨场景保留(默认保留)
protected virtual bool IsDontDestroy => true;
protected virtual void Awake()
{
// 已有实例且不是自己 → 销毁多余的
if (Instance != null && Instance != this)
{
Destroy(gameObject);
return;
}
Instance = (T)this;
if (IsDontDestroy)
DontDestroyOnLoad(gameObject);
}
protected virtual void OnDestroy()
{
// 自己被销毁时清空引用,避免访问到已销毁的对象
if (Instance == this)
Instance = null;
}
}

非继承 Mono 泛型单例#

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