泛型單例模式
阿新 • • 發佈:2022-05-27
當遊戲內需要多個Manager時,可以使用泛型單例來簡化我們的程式碼。
1 using System.Collections; 2 using System.Collections.Generic; 3 using UnityEngine; 4 5 //泛型單例 6 public class Singleton<T> : MonoBehaviour where T:Singleton<T> 7 { 8 private static T instance; 9 10 public static T Instance 11 {12 get { return instance; } 13 } 14 15 protected virtual void Awake() 16 { 17 if(instance!= null) 18 Destroy(gameObject); 19 else 20 instance = (T)this; 21 } 22 23 //判斷是否已經生成 24 public static bool IsInitialized 25 { 26 get{ return instance != null; } 27 } 28 29 //銷燬時置空 30 protected virtual void OnDestory() 31 { 32 if(instance == this) 33 { 34 instance = null; 35 } 36 } 37 }
繼承該模板類,即可實現單例模式
1 using System.Collections; 2 using System.Collections.Generic; 3 usingUnityEngine; 4 5 public class GameManager : Singleton<GameManager> 6 { 7 8 protected override void Awake() 9 { 10 base.Awake(); 11 //DontDestroyOnLoad(); 12 } 13 14 }