/// <summary> /// A static instance is similar to a singleton, but instead of destroying any new /// instances, it overrides the current instance. This is handy for resetting the state /// and saves you doing it manually /// </summary> public abstract class StaticInstance<T> : MonoBehaviour where T : MonoBehaviour { public static T Instance { get; private set; } protected virtual void Awake() => Instance = this as T; protected virtual void OnApplicationQuit() { Instance = null; Destroy(gameObject); } } /// <summary> /// This transforms the static instance into a basic singleton. This will destroy any new /// versions created, leaving the original instance intact /// ///这将把静态实例转换成一个基本的单例。这将摧毁任何新的 ///创建的版本,保留原来的实例不变 /// </summary> public abstract class Singleton<T> : StaticInstance<T> where T : MonoBehaviour { protected override void Awake() { if (Instance != null) Destroy(gameObject); base.Awake(); } }
/// <summary> //最后,我们有了一个持久版本的单例。这将通过现场生存 /// / / 负载。非常适合需要有状态、持久数据的系统类。或音频来源 ///通过加载屏幕播放音乐,等等 /// </summary> public abstract class PersistentSingleton<T> : Singleton<T> where T : MonoBehaviour { protected override void Awake() { base.Awake(); DontDestroyOnLoad(gameObject); } }