using System; using Sirenix.OdinInspector; using UnityEngine; namespace UnityTest.ZXL { /// /// 继承MonoBehavior的单例基类 /// /// public abstract class BaseAutoMono : SerializedMonoBehaviour where T : MonoBehaviour { private static T instance; public static T Instance() { if (instance == null) { var findObjectsOfType = GameObject.FindObjectsOfType(); if (findObjectsOfType.Length > 1) { throw new Exception($"{typeof(T)}' count is larger than 1"); } if (findObjectsOfType.Length == 0) { GameObject go = new GameObject(); go.name = typeof(T).ToString(); DontDestroyOnLoad(go); instance = go.AddComponent(); } else { instance = findObjectsOfType[0]; } } return instance; } void Awake() { instance = this.gameObject.GetComponent(); } } }