using UnityEngine; public class MonoSingleton : MonoBehaviour where T : MonoSingleton { private static T instance; public static T Instance { get { // 如果实例不存在,尝试在场景中查找 if (instance == null) { instance = FindFirstObjectByType(); // 如果还没找到,创建一个新的 GameObject 并挂载组件 if (instance == null) { GameObject go = new GameObject(typeof(T).Name); instance = go.AddComponent(); // 可选:设置为跨场景不销毁 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 { public AudioSource audioSource; protected override void Initialize() { Debug.Log("AudioManager 初始化"); audioSource = gameObject.AddComponent(); } public void PlaySound(AudioClip clip) { audioSource.PlayOneShot(clip); } } // 使用方式 public class Player : MonoBehaviour { //void OnTriggerEnter(Collider other) //{ //AudioManager.Instance.PlaySound(hitSound); //} }