泛型单例模式
当游戏内需要多个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 using UnityEngine; 4 5 public class GameManager : Singleton<GameManager> 6 { 7 8 protected override void Awake() 9 { 10 base.Awake(); 11 //DontDestroyOnLoad(); 12 } 13 14 }

浙公网安备 33010602011771号