55 lines
1.5 KiB
C#
55 lines
1.5 KiB
C#
using UnityEngine;
|
|
|
|
namespace Roy
|
|
{
|
|
|
|
public class SingletonMonoBehaviour<T> : MonoBehaviour where T : MonoBehaviour
|
|
{
|
|
private static T _instance;
|
|
|
|
public static T Instance
|
|
{
|
|
get
|
|
{
|
|
if (_instance == null)
|
|
{
|
|
// 尝试找到已存在的实例
|
|
_instance = FindObjectOfType<T>();
|
|
|
|
// 如果没有找到,则创建一个新的实例
|
|
if (_instance == null)
|
|
{
|
|
GameObject singletonObject = new GameObject(typeof(T).Name);
|
|
_instance = singletonObject.AddComponent<T>();
|
|
DontDestroyOnLoad(singletonObject); // 不在场景切换时销毁
|
|
}
|
|
}
|
|
|
|
return _instance;
|
|
}
|
|
}
|
|
|
|
// 确保在场景中只存在一个实例
|
|
protected virtual void Awake()
|
|
{
|
|
if (_instance == null)
|
|
{
|
|
_instance = this as T;
|
|
}
|
|
else if (_instance != this)
|
|
{
|
|
Debug.LogWarning($"An instance of {typeof(T)} already exists! Destroying this instance.");
|
|
Destroy(gameObject); // 如果有其他实例,销毁当前对象
|
|
}
|
|
}
|
|
|
|
protected virtual void OnDestroy()
|
|
{
|
|
if (_instance == this)
|
|
{
|
|
_instance = null; // 清除引用
|
|
}
|
|
}
|
|
}
|
|
|
|
} |