using System; public class Singleton<T> where T : class, new() { private static T m_instance; public static T instance { get { if (Singleton<T>.m_instance == null) { Singleton<T>.CreateInstance(); } return Singleton<T>.m_instance; } } protected Singleton() { } public static void CreateInstance() { if (Singleton<T>.m_instance == null) { Singleton<T>.m_instance = Activator.CreateInstance<T>(); (Singleton<T>.m_instance as Singleton<T>).Init(); } } public static void DestroyInstance() { if (Singleton<T>.m_instance != null) { (Singleton<T>.m_instance as Singleton<T>).UnInit(); Singleton<T>.m_instance = (T)((object)null); } } public static T GetInstance() { if (Singleton<T>.m_instance == null) { Singleton<T>.CreateInstance(); } return Singleton<T>.m_instance; } public static bool HasInstance() { return Singleton<T>.m_instance != null; } public virtual void Init() { } public virtual void UnInit() { } }
using UnityEngine; public class MonoSingleton<T> : MonoBehaviour where T : MonoBehaviour { private static bool applicationIsQuitting = false; private static T _instance; private static object _lock = new object(); public static T Instance { get { if (applicationIsQuitting) { Debug.LogWarning("[Singleton] Instance " + typeof(T) + " already destroyed on application quit." + "Won‘t create again - returning null."); return null; } lock (_lock) { if (_instance == null) { _instance = (T)FindObjectOfType(typeof(T)); if (_instance == null) { GameObject singleton = new GameObject(); _instance = singleton.AddComponent<T>(); singleton.name = "(singleton) " + typeof(T).ToString(); DontDestroyOnLoad(singleton); Debug.Log("[Singleton] An instance of " + typeof(T) + " is needed in the scene, so ‘" + singleton + "‘ was created with DontDestroyOnLoad."); } else { Debug.Log("[Singleton] Using instance already created: " + _instance.gameObject.name); } } return _instance; } } } /////////////////////////////////////////// private void Awake() { Init(); } private void Update() { Tick(); } private void OnDestroy() { applicationIsQuitting = true; UnInit(); } /////////////////////////////////////////// protected virtual void Init() { } protected virtual void UnInit() { } protected virtual void Tick() { } }
时间: 2024-10-25 18:09:21