using UnityEngine; public class Singleton : MonoBehaviour where T : MonoBehaviour { private static T _instance; public static T Instance { get { if (_instance == null) { _instance = (T)FindObjectOfType(typeof(T)); if (_instance == null) { Debug.LogError("An instance of " + typeof(T) + " is needed in the scene, but there is none."); } } return _instance; } } public bool persistThroughScene = false; protected virtual void Awake() { if (_instance == null) { _instance = this as T; if (persistThroughScene) { DontDestroyOnLoad(gameObject); } } else { Destroy(gameObject); } } }