Unity通用泛型單例設(shè)計(jì)模式(普通型和繼承自MonoBehaviour)
單例模式是設(shè)計(jì)模式中最為常見的,不多解釋了。但應(yīng)該盡量避免使用,一般全局管理類才使用單例。
普通泛型單例:
public abstract class Singleton<T> where T : class, new()
{
private static T instance = null;
private static readonly object locker = new object();
public static T Instance
{
get
{
lock (locker)
{
if (instance == null)
instance = new T();
return instance;
}
}
}
}
繼承MonoBehaviour的泛型單例:
using UnityEngine;
public abstract class MonoSingleton <T>: MonoBehaviour where T:MonoBehaviour
{
private static T instance = null;
private static readonly object locker = new object();
private static bool bAppQuitting;
public static T Instance
{
get
{
if (bAppQuitting)
{
instance = null;
return instance;
}
lock (locker)
{
if (instance == null)
{
instance = FindObjectOfType<T>();
if (FindObjectsOfType<T>().Length > 1)
{
Debug.LogError("不應(yīng)該存在多個(gè)單例!");
return instance;
}
if (instance == null)
{
var singleton = new GameObject();
instance = singleton.AddComponent<T>();
singleton.name = "(singleton)" + typeof(T);
singleton.hideFlags = HideFlags.None;
DontDestroyOnLoad(singleton);
}
else
DontDestroyOnLoad(instance.gameObject);
}
instance.hideFlags = HideFlags.None;
return instance;
}
}
}
private void Awake()
{
bAppQuitting = false;
}
private void OnDestroy()
{
bAppQuitting = true;
}
}
使用方法直接用類去繼承這兩個(gè)抽象單例即可,使用T.Instance就可以直接取得該類(T)的唯一實(shí)例了。
以上就是Unity通用泛型單例設(shè)計(jì)模式(普通型和繼承自MonoBehaviour)的詳細(xì)內(nèi)容,更多關(guān)于unity單例設(shè)計(jì)模式的資料請關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
C#調(diào)用sql2000存儲(chǔ)過程方法小結(jié)
這篇文章主要介紹了C#調(diào)用sql2000存儲(chǔ)過程的方法,以實(shí)例形式分別對調(diào)用帶輸入?yún)?shù)及輸出參數(shù)的存儲(chǔ)過程進(jìn)行了詳細(xì)分析,非常具有實(shí)用價(jià)值,需要的朋友可以參考下2014-10-10
C# HttpClient Post參數(shù)同時(shí)上傳文件的實(shí)現(xiàn)
這篇文章主要介紹了C# HttpClient Post參數(shù)同時(shí)上傳文件的實(shí)現(xiàn),具有很好的參考價(jià)值,希望對大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2022-06-06

