生活随笔
收集整理的這篇文章主要介紹了
Unity3D 单例模式
小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
簡(jiǎn)潔
在游戲開(kāi)發(fā)中會(huì)經(jīng)常使用到單例模式,什么時(shí)候會(huì)用到單例模式呢?有一些數(shù)據(jù)會(huì)在整個(gè)游戲(程序)生命中一直持續(xù)到游戲結(jié)束的數(shù)據(jù)。例如:玩家數(shù)據(jù)。
代碼
提供兩種單例:
C#中的單例。Unity3D繼承MonoBehaviour的單例。
using UnityEngine;namespace Singleton
{public abstract class Singleton<T> where T : new(){static object _lock
= new object();private static T _instance
;public static T Instance
{get{if (_instance
== null){lock (_lock
){if (_instance
== null){_instance
= new T();}}}return _instance
;}}public virtual void Release(){_instance
= default(T);}}public class SingletonMono<T> : MonoBehaviour where T : Component{private static bool _isApplicationQuit
= false;private static T _instance
;public bool IsLive
{get{if (_instance
== null){return false;}return !_isApplicationQuit
;}}public static T Instance
{get{if (_instance
== null && !_isApplicationQuit
){_instance
= FindObjectOfType(typeof(T)) as T;if (_instance
== null){GameObject obj
= new GameObject();obj
.name
= typeof(T).Name
.ToString();_instance
= (T
)obj
.AddComponent(typeof(T));}if (Application
.isPlaying
){GameObject
.DontDestroyOnLoad(_instance
);}}return _instance
;}}protected virtual void OnApplicationQuit(){_isApplicationQuit
= true;}protected virtual void OnDestory(){_isApplicationQuit
= true;_instance
= null;}}
}
總結(jié)
以上是生活随笔為你收集整理的Unity3D 单例模式的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
如果覺(jué)得生活随笔網(wǎng)站內(nèi)容還不錯(cuò),歡迎將生活随笔推薦給好友。