using System; using UnityEngine; namespace BitStrap { public class Singleton : MonoBehaviour where T : MonoBehaviour { private static T instance; public static T Instance { get { return GetInstance(true); } } public static void RequireInstance(Action callback) { T val = GetInstance(false); if (val != null && callback != null) { callback(val); } } public static T GetInstance(bool warnIfNotFound) { if (instance == null) { instance = UnityEngine.Object.FindObjectOfType(); if (instance == null && warnIfNotFound) { OnInstanceNotFound(); } } return instance; } protected void ForceSingletonInstance() { instance = this as T; } protected virtual void OnDestroy() { instance = (T)null; } private static void OnInstanceNotFound() { Debug.LogWarningFormat("Didn't find a object of type {0}!", typeof(T).Name); } } }