using System; using UnityEngine; public class Singleton : MonoBehaviour where T : MonoBehaviour { private static T _instance; public static T Instance { get { if (_instance == null) { _instance = FindObjectOfType(); if (_instance == null) { GameObject obj = new GameObject(); obj.name = typeof(T).Name; _instance = obj.AddComponent(); } } return _instance; } } protected virtual void Awake() { if (_instance == null) { _instance = this as T; OnLoad(); DontDestroyOnLoad(gameObject); } else { Destroy(gameObject); } } private void Update() { OnUpdate(); } #region 生命周期 protected virtual void OnLoad() { } protected virtual void OnUpdate() { } #endregion }