using System; using UnityEngine; namespace RayNeo.Native { /// /// Mono单例 /// public abstract class MonoSingleton : MonoBehaviour where T : MonoSingleton { private static T m_Instance; /// /// 单例对象 /// public static T Instance { get { if (m_Instance == null) { T[] ts = GameObject.FindObjectsOfType(); if (ts != null && ts.Length > 0) { if (ts.Length == 1) { m_Instance = ts[0]; } else { throw new Exception(string.Format("## Uni Exception ## Cls:{0} Info:Singleton not allows more than one instance", typeof(T))); } } else { m_Instance = new GameObject(string.Format("{0}(Singleton)", typeof(T).ToString())).AddComponent(); m_Instance.OnSingletonInit(); } } return m_Instance; } } protected MonoSingleton() { } protected virtual void Awake() { m_Instance = this as T; //DontDestroyOnLoad(this.gameObject); } protected virtual void OnDestroy() { m_Instance = null; } protected virtual void OnSingletonInit() { } } }