Unity Singleton 单例类(Unity3D开发)
一、添加单例模板类
1 using UnityEngine; 2 3 public class Singleton<T> : MonoBehaviour where T : MonoBehaviour 4 { 5 private static T _instance; 6 7 private static object _lock = new object (); 8 9 public static T Instance 10 { 11 get { 12 if (applicationIsQuitting) { 13 return null; 14 } 15 16 lock (_lock) { 17 if (_instance == null) { 18 _instance = (T)FindObjectOfType (typeof(T)); 19 20 if (FindObjectsOfType (typeof(T)).Length > 1) { 21 return _instance; 22 } 23 24 if (_instance == null) { 25 GameObject singleton = new GameObject (); 26 _instance = singleton.AddComponent<T> (); 27 singleton.name = "(singleton) " + typeof(T).ToString (); 28 29 DontDestroyOnLoad (singleton); 30 } 31 } 32 33 return _instance; 34 } 35 } 36 } 37 38 private static bool applicationIsQuitting = false; 39 40 public void OnDestroy () 41 { 42 applicationIsQuitting = true; 43 } 44 }
这是一个单例模板类,使用就很简单了。
二、定义自己的单例类
1 using UnityEngine; 2 using System.Collections; 3 4 public class InstanceTest : Singleton<InstanceTest> 5 { 6 internal string mName = "InstanceTest"; 7 }
三、调用使用
1 Debug.Log(InstanceTest.Instance.mName);
打印
以上根据某社区的文章练习代码,Unity版本5.4.4,使用正常
参考文章:Cocos2Der-CSDN http://blog.csdn.net/cocos2der/article/details/47335197