Forest_Client/Forest/Assets/PhxhSDK/Phxh/SingletonMono.cs

1 line
2.6 KiB
C#
Raw Normal View History

2024-06-12 15:01:54 +08:00
using UnityEngine; namespace PhxhSDK { public class SingletonMono<T> : 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; /// <summary> /// Access singleton instance through this propriety. /// </summary> 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<T>(); singletonObject.name = typeof(T) + " (Singleton)"; singletonObject.hideFlags = HideFlags.HideInHierarchy; // Make instance persistent. if (Application.isPlaying) { // 有人在非运行状态下调用Instance不要设置DontDestroyOnLoad DontDestroyOnLoad(singletonObject); } (m_Instance as SingletonMono<T>)?.InitImmediately(); } } return m_Instance; } } } private void OnApplicationQuit() { m_ShuttingDown = true; } // 这个方法如果override会在Instance创建完立刻调用, 派生类可以用来默认初始化一些东西 protected virtual void InitImmediately() { } } }