using System; using UnityEngine; public class DestroyableSingleton : MonoBehaviour where T : MonoBehaviour { public static bool InstanceExists { get { return DestroyableSingleton._instance; } } public static T Instance { get { if (!DestroyableSingleton._instance) { DestroyableSingleton._instance = UnityEngine.Object.FindObjectOfType(); if (!DestroyableSingleton._instance) { DestroyableSingleton._instance = new GameObject().AddComponent(); } } return DestroyableSingleton._instance; } } private static T _instance; public bool DontDestroy; public virtual void Awake() { if (!DestroyableSingleton._instance) { DestroyableSingleton._instance = (this as T); if (this.DontDestroy) { UnityEngine.Object.DontDestroyOnLoad(base.gameObject); return; } } else if (DestroyableSingleton._instance != this) { UnityEngine.Object.Destroy(base.gameObject); } } public virtual void OnDestroy() { if (!this.DontDestroy) { DestroyableSingleton._instance = default(T); } } }