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