using UnityEngine; public class MBSingletonManager : MonoBehaviour where T : MonoBehaviour { /// /// 存储唯一实例的私有静态变量 /// private static T instance; /// /// 用于锁定的对象 /// private static readonly object mlock = new object(); /// /// 公共静态属性用于访问实例 /// public static T Instance { get { // 使用锁确保线程安全 lock (mlock) { if (instance == null)//如果实例为空,则寻找现有的实例 { instance = FindObjectOfType(); if (instance == null)//如果场景中没有找到实例,则创建一个新的 { GameObject singletonObject = new GameObject(typeof(T).Name); instance = singletonObject.AddComponent(); } DontDestroyOnLoad(instance); //保持单例在场景切换时不被销毁 } return instance; } } } /// /// 释放单例 /// public virtual void ReleaseInstance() { if (instance != null) { Destroy(instance.gameObject); instance = null; // 释放引用 } } }