using UnityEngine; namespace FirstVillain.Singleton { public class UnitySingleton : MonoBehaviour where T : UnityEngine.Component { private static T _instance = null; public static T Instance { get { if (_instance == null) { string name = (typeof(T)).ToString(); _instance = new GameObject(name).AddComponent(); } return _instance; } } private void Awake() { if (_instance != null && _instance != this) { Destroy(gameObject); return; } else { _instance = this as T; } DontDestroyOnLoad(gameObject); AwakeSingleton(); } private void OnDestroy() { if (_instance == this) { _instance = null; } } protected virtual void AwakeSingleton() { } } public class UnitySingletonOnce : MonoBehaviour where T : UnityEngine.Component { private static T _instance = null; public static T Instance { get { if (_instance == null) { string name = (typeof(T)).ToString(); _instance = new GameObject(name).AddComponent(); } return _instance; } } private void Awake() { if (_instance != null && _instance != this) { Destroy(gameObject); return; } else { _instance = this as T; } AwakeSingleton(); } private void OnDestroy() { if (_instance == this) { _instance = null; } } protected virtual void AwakeSingleton() { } } }