using System; using UnityEngine; public abstract class SingletonMono : MonoBehaviour where T : MonoBehaviour { private static volatile T instance; private static readonly object lockObj = new object(); public static T Instance { get { if (instance == null) { lock (lockObj) { if (instance == null) { instance = CreateInstance(); } } } return instance; } } protected virtual void Awake() { if (instance != null && instance != this) { DestroyImmediate(this); return; } instance = this as T; DontDestroyOnLoad(gameObject); } public virtual void Destroy() { if (instance != null) { lock (lockObj) { if (instance != null) { instance = null; } } } } private static T CreateInstance() { try { return (T)Activator.CreateInstance(typeof(T), nonPublic: true); } catch (MissingMethodException ex) { throw new InvalidOperationException( $"{typeof(T).Name} must have a non-public parameterless constructor", ex); } } }