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 }
View Code

這是一個單例模板類,使用就很簡單了。

二、定義自己的單例類

1 using UnityEngine;
2 using System.Collections;
3 
4 public class InstanceTest : Singleton<InstanceTest>
5 {
6     internal string mName = "InstanceTest";
7 }
View Code

三、調用使用

1 Debug.Log(InstanceTest.Instance.mName);
View Code

打印

以上根據某社區的文章練習代碼,Unity版本5.4.4,使用正常

參考文章:Cocos2Der-CSDN http://blog.csdn.net/cocos2der/article/details/47335197


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM