using System; using UnityEngine; public class Singleton : BaseBehaviour where T : BaseBehaviour { private static bool m_ShuttingDown = false; private static object m_Lock = new object(); private static T m_Instance; // 单例对象在切换场景时不销毁 public virtual void Awake() { DontDestroyOnLoad(gameObject); } /// /// 单例 /// public static T Instance { get { if (m_ShuttingDown) { Debug.LogWarning($"[{typeof(T)}]已经销毁"); return null; } lock (m_Lock) { if (m_Instance == null) { // 找到单例对象 m_Instance = (T)FindObjectOfType(typeof(T)); // 对象为空创建新对象 if (m_Instance == null) { // 创建一个空对象 var singletonObject = new GameObject(); m_Instance = singletonObject.AddComponent(); singletonObject.name = $"[{typeof(T).ToString()}]"; // Make instance persistent. //DontDestroyOnLoad(singletonObject); } } return m_Instance; } } } public virtual void Initialize() { } private void OnApplicationQuit() { m_ShuttingDown = true; } private void OnDestroy() { m_ShuttingDown = true; } }