using UnityEngine; namespace X10D.Unity; /// /// Represents a class which implements the singleton pattern for a specific . This class is not /// thread-safe. /// /// The type of the singleton. public abstract class Singleton : MonoBehaviour where T : Singleton { private static Lazy s_instanceLazy = new(CreateLazyInstanceInternal, false); private static T? s_instance; /// /// Gets the instance of the singleton. /// /// The singleton instance. public static T Instance { get => s_instance ? s_instance! : s_instanceLazy.Value; } /// /// Called when the script instance is being loaded. /// protected virtual void Awake() { s_instance = (T?)this; } /// /// Called when the object is destroyed. /// protected virtual void OnDestroy() { s_instance = null; s_instanceLazy = new Lazy(CreateLazyInstanceInternal, false); } private static T CreateLazyInstanceInternal() { if (s_instance) { return s_instance!; } if (FindObjectOfType() is { } instance) { s_instance = instance; return instance; } var gameObject = new GameObject {name = typeof(T).Name}; return s_instance = gameObject.AddComponent(); } }