/// <summary> /// 获取到单例,若无法获取到则返回异常; /// </summary> /// <exception cref="GameObjectNotFoundException"></exception> /// <exception cref="ComponentNotFoundException"></exception> public T GetInstance() { lock (asyncLock) { if (instance != null) { return(instance); } if (UnityThread.IsUnityThread) { #if UNITY_EDITOR if (UnityThread.IsEditMode) { Debug.LogWarning("在编辑模式下进行了单例访问;"); return(Find()); } #endif return(instance ?? (instance = Find())); } else { #if UNITY_EDITOR if (UnityThread.IsEditMode) { Debug.LogWarning("在编辑模式下进行了单例访问;"); return(UnityThread.Run(Find).Result); } #endif return(instance ?? (instance = UnityThread.Run(Find).Result)); } } }
/// <summary> /// 添加 观察者 到 Unity.Debug.unityLogger.logHandler;(仅Unity线程调用) /// </summary> public static IDisposable Subscribe(IObserver <UnityDebugLogEvent> observer) { UnityThread.ThrowIfNotUnityThread(); if (observer == null) { throw new ArgumentNullException(nameof(observer)); } if (defaultLogHandler == null) { defaultLogHandler = Debug.unityLogger.logHandler; Debug.unityLogger.logHandler = new LogHandler(); } return(observers.Subscribe(observer)); }
/// <summary> /// 搜索获取到单例; /// </summary> /// <exception cref="GameObjectNotFoundException"></exception> /// <exception cref="ComponentNotFoundException"></exception> /// <exception cref="InvalidOperationException">当非Unity线程调用时</exception> public T Find() { UnityThread.ThrowIfNotUnityThread(); GameObject sceneController = GameObject.FindWithTag(ControllerTagName); if (sceneController != null) { var instance = sceneController.GetComponentInChildren <T>(); if (instance == null) { throw new ComponentNotFoundException(string.Format("未找到类型[{0}]", typeof(T).FullName)); } else { return(instance); } } else { throw new GameObjectNotFoundException(string.Format("未找到标签[{0}]", ControllerTagName)); } }