【Unity】遊戲中的單例

遊戲中須要一些 GameObject(例如網絡管理器) 在遊戲的整個生命週期都存在,並且是以單例的形式存在。網絡

 XGame 中實現這種單例的方式是,單例腳本都從 MonoSingle 類繼承,MonoSingleton 的實現方法是在 Awake() 中調用 DontDestroyOnLoad(gameObject);來保證單例。
MonoSingleton類的實現代碼:
 1 /// <summary>
 2 /// Generic Mono singleton.
 3 /// </summary>
 4 using UnityEngine;
 5 
 6 public abstract class MonoSingleton<T> : MonoBehaviour where T : MonoSingleton<T>{
 7     
 8     private static T mInstance = null;
 9     
10     public static T Instance{
11         get{
12             return mInstance;
13         }
14     }
15 
16     private void Awake(){
17    
18         if (mInstance == null)
19         {
20             DontDestroyOnLoad(gameObject);
21             mInstance = this as T;
22             mInstance.Init();
23         }
24         else
25         {
26             Destroy(gameObject);
27         }
28     }
29  
30     public virtual void Init(){}
31 
32     public virtual void Fini(){}
33  
34 
35     private void OnApplicationQuit(){
36         mInstance.Fini();
37         mInstance = null;
38     }
39 }

須要單例控制的腳本,只要從 MonoSigleton 類繼承就能夠了,重寫 Init 方法來實現單例本身的初始化,重寫 Fini 實現本身的清理工做。例如:ui

相關文章
相關標籤/搜索