/* ######### ############ ############# ## ########### ### ###### ##### ### ####### #### ### ########## #### #### ########### #### #### ########### ##### ##### ### ######## ##### ##### ### ######## ###### ###### ### ########### ###### ###### #### ############## ###### ####### ##################### ###### ####### ###################### ###### ####### ###### ################# ###### ####### ###### ###### ######### ###### ####### ## ###### ###### ###### ####### ###### ##### ##### ###### ##### ##### #### ##### #### ##### ### ##### ### ### # ### ### ### ## ### ### __________#_______####_______####______________ 身是菩提树,心如明镜台,时时勤拂拭,勿使惹尘埃。 我们的未来没有BUG * ============================================================================== * Filename: Instering * Created: 2017/8/1 * Author: WYC * Purpose: 单例模式 * ============================================================================== */ using UnityEngine; public class Singleton<T> : MonoBehaviour where T : MonoBehaviour{ private static T _instance; private static object _look = new object(); public static T instance{ get{ if (applicationIsQuitting) { Debug.LogWarning("[Singleton] Instance '"+ typeof(T) + "在应用程序退出时已经被销毁了" + "不会再创建-返回null"); return null; } lock (_look) { if (_instance == null) { _instance = (T) FindObjectOfType(typeof(T)); if ( FindObjectsOfType(typeof(T)).Length > 1 ) { Debug.LogError("[Singleton] Something went really wrong " + "永远不要超过1个单例!" + "重新开放这个场景可能会修复它。"); return _instance; } if (_instance == null) { GameObject singleton = new GameObject(); _instance = singleton.AddComponent<T>(); singleton.name = "(singleton) "+ typeof(T).ToString(); DontDestroyOnLoad(singleton); Debug.Log("[Singleton] An instance of " + typeof(T) + " 在场景中是必要的 '" + singleton + " 是用dont摧毁的负载创建的 "); } else { Debug.Log("[Singleton] 使用已经创建实例: " + _instance.gameObject.name); } } return _instance; } } } private static bool applicationIsQuitting = false; public void OnDestory(){ applicationIsQuitting = true; } }