58 lines
1.4 KiB
C#
58 lines
1.4 KiB
C#
using UnityEngine;
|
|
|
|
public class MonoSingleton<T> : MonoBehaviour where T : MonoSingleton<T>
|
|
{
|
|
private static T instance;
|
|
public static T Instance
|
|
{
|
|
get
|
|
{
|
|
// 如果实例不存在,尝试在场景中查找
|
|
if (instance == null)
|
|
{
|
|
instance = FindFirstObjectByType<T>();
|
|
|
|
// 如果还没找到,创建一个新的 GameObject 并挂载组件
|
|
if (instance == null)
|
|
{
|
|
GameObject go = new GameObject(typeof(T).Name);
|
|
instance = go.AddComponent<T>();
|
|
|
|
// 可选:设置为跨场景不销毁
|
|
DontDestroyOnLoad(go);
|
|
}
|
|
}
|
|
return instance;
|
|
}
|
|
}
|
|
|
|
protected virtual void Awake()
|
|
{
|
|
// 确保只有一个实例
|
|
if (instance != null && instance != this)
|
|
{
|
|
Destroy(this.gameObject);
|
|
return;
|
|
}
|
|
|
|
instance = this as T;
|
|
|
|
// 如果需要跨场景,在这里调用 DontDestroyOnLoad
|
|
DontDestroyOnLoad(this.gameObject);
|
|
|
|
Initialize();
|
|
}
|
|
|
|
protected virtual void Initialize()
|
|
{
|
|
// 供子类重写的初始化方法
|
|
}
|
|
|
|
protected virtual void OnDestroy()
|
|
{
|
|
if (instance == this)
|
|
{
|
|
instance = null;
|
|
}
|
|
}
|
|
} |