using UnityEngine; using System.Collections; namespace BF { public class MonoSingleton : MonoBehaviour where T : Component { bool inited; static T instance; public static T Instance { get { if (instance == null) { instance = FindObjectOfType(typeof(T)) as T; if (instance == null) { var obj = new GameObject(); #if UNITY_EDITOR obj.hideFlags = HideFlags.DontSave; #else obj.hideFlags = HideFlags.HideAndDontSave; #endif obj.name = typeof(T).ToString(); instance = (T)obj.AddComponent(typeof(T)); } else { var ms = instance as MonoSingleton; ms.Init(); } } return instance; } } protected virtual void Init() { if (inited) { return; } inited = true; } protected virtual void Awake() { DontDestroyOnLoad(gameObject); if (instance == null) { #if UNITY_EDITOR gameObject.hideFlags = HideFlags.DontSave; #else gameObject.hideFlags = HideFlags.HideAndDontSave; #endif gameObject.name = typeof(T).ToString(); instance = this as T; var ms = instance as MonoSingleton; ms.Init(); } } } }