Unity Singleton 单例类(Unity3D开发)

时间:2023-03-08 16:34:54

一、添加单例模板类

 using UnityEngine;

 public class Singleton<T> : MonoBehaviour where T : MonoBehaviour
{
private static T _instance; private static object _lock = new object (); public static T Instance
{
get {
if (applicationIsQuitting) {
return null;
} lock (_lock) {
if (_instance == null) {
_instance = (T)FindObjectOfType (typeof(T)); if (FindObjectsOfType (typeof(T)).Length > ) {
return _instance;
} if (_instance == null) {
GameObject singleton = new GameObject ();
_instance = singleton.AddComponent<T> ();
singleton.name = "(singleton) " + typeof(T).ToString (); DontDestroyOnLoad (singleton);
}
} return _instance;
}
}
} private static bool applicationIsQuitting = false; public void OnDestroy ()
{
applicationIsQuitting = true;
}
}

这是一个单例模板类,使用就很简单了。

二、定义自己的单例类

 using UnityEngine;
using System.Collections; public class InstanceTest : Singleton<InstanceTest>
{
internal string mName = "InstanceTest";
}

三、调用使用

 Debug.Log(InstanceTest.Instance.mName);

打印

Unity Singleton 单例类(Unity3D开发)

以上根据某社区的文章练习代码,Unity版本5.4.4,使用正常

参考文章:Cocos2Der-**** http://blog.****.net/cocos2der/article/details/47335197