using UnityEngine; namespace MoreMountains.Tools { /// /// Singleton pattern. /// public class MMSingleton : MonoBehaviour where T : Component { protected static T _instance; public static bool HasInstance => _instance != null; public static T TryGetInstance() => HasInstance ? _instance : null; public static T Current => _instance; /// /// Singleton design pattern /// /// The instance. public static T Instance { get { if (_instance == null) { _instance = FindObjectOfType (); if (_instance == null) { GameObject obj = new GameObject (); obj.name = typeof(T).Name + "_AutoCreated"; _instance = obj.AddComponent (); } } return _instance; } } /// /// On awake, we initialize our instance. Make sure to call base.Awake() in override if you need awake. /// protected virtual void Awake () { InitializeSingleton(); } /// /// Initializes the singleton. /// protected virtual void InitializeSingleton() { if (!Application.isPlaying) { return; } _instance = this as T; } } }