public class Singleton<T> : MonoBehaviour where T : Singleton<T> { public static T Instance { get; private set; } public bool isInitialized => Instance != null;
protected virtual void Awake() { if (Instance != null) Destroy(gameObject); else Instance = (T) this; }
protected virtual void OnDestroy() { if (Instance == this) { Instance = null; } } }
|
在继承于Singleton的子类中,可以使用override关键字对其中的virtual方法进行重写
protected override void Awake() { base.Awake(); DontDestroyOnLoad(this); }
|
其中base.Awake()指执行父类中的awake函数,与java中的super相似