EnergyEfficiencyManagement/Assets/Zion/Scripts/Utils/MonoSingleton.cs

84 lines
1.9 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;
}
}
}
// 具体管理器继承 MonoBehaviour 单例
public class AudioManager : MonoSingleton<AudioManager>
{
public AudioSource audioSource;
protected override void Initialize()
{
Debug.Log("AudioManager 初始化");
audioSource = gameObject.AddComponent<AudioSource>();
}
public void PlaySound(AudioClip clip)
{
audioSource.PlayOneShot(clip);
}
}
// 使用方式
public class Player : MonoBehaviour
{
//void OnTriggerEnter(Collider other)
//{
//AudioManager.Instance.PlaySound(hitSound);
//}
}