using UnityEngine; namespace PhxhSDK { public class SingletonMono : MonoBehaviour where T : MonoBehaviour { // Check to see if we're about to be destroyed. private static bool m_ShuttingDown; private static readonly object m_Lock = new(); private static T m_Instance; /// /// Access singleton instance through this propriety. /// public static T Instance { get { if (!Application.isPlaying) { Debug.LogError("[Singleton] Instance '" + typeof(T) + "' not found. (非运行状态下调用Instance)"); return null; } #if UNITY_EDITOR if (m_ShuttingDown) { DebugUtil.LogWarning("[Singleton] Instance '" + typeof(T) + "' already destroyed. Returning null."); return null; } #endif lock (m_Lock) { if (m_Instance == null) { // Search for existing instance. m_Instance = (T)FindObjectOfType(typeof(T)); // Create new instance if one doesn't already exist. if (m_Instance == null) { // Need to create a new GameObject to attach the singleton to. var singletonObject = new GameObject(); m_Instance = singletonObject.AddComponent(); singletonObject.name = typeof(T) + " (Singleton)"; singletonObject.hideFlags = HideFlags.HideInHierarchy; // Make instance persistent. if (Application.isPlaying) { // 有人在非运行状态下调用Instance,不要设置DontDestroyOnLoad DontDestroyOnLoad(singletonObject); } (m_Instance as SingletonMono)?.InitImmediately(); } } return m_Instance; } } } private void OnApplicationQuit() { m_ShuttingDown = true; } // 这个方法如果override,会在Instance创建完立刻调用, 派生类可以用来默认初始化一些东西 protected virtual void InitImmediately() { } } }