Unity里面两种单例模式的实现
Posted Carlos
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Unity里面两种单例模式的实现相关的知识,希望对你有一定的参考价值。
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() { } }
以上是关于Unity里面两种单例模式的实现的主要内容,如果未能解决你的问题,请参考以下文章