1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283 |
- // Copyright (c) Microsoft Corporation. All rights reserved.
- // Licensed under the MIT License. See LICENSE in the project root for license information.
- using System;
- using UnityEngine;
- namespace XRTool.Util
- {
- /// <summary>
- /// Unity的单例
- /// Singleton behaviour class, used for components that should only have one instance
- ///
- /// </summary>
- /// <typeparam name="T"></typeparam>
- public abstract class UnitySingleton<T> : MonoBehaviour where T : UnitySingleton<T>
- {
- public static event Action InitComplte;
- public static event Action DeleteSingle;
- private static T instance;
- public static T Instance
- {
- get
- {
- return instance;
- }
- }
- /// <summary>
- /// Returns whether the instance has been initialized or not.
- /// </summary>
- public static bool IsInitialized
- {
- get
- {
- return instance != null;
- }
- }
- /// <summary>
- /// 强制实例化某对象
- /// 注意此操作不是同步完成的
- /// </summary>
- public static void ForceInstance()
- {
- if (!instance)
- {
- GameObject obj = new GameObject();
- obj.AddComponent<T>();
- }
- }
- /// <summary>
- /// Base awake method that sets the singleton's unique instance.
- /// </summary>
- protected virtual void Awake()
- {
- if (instance != null && instance.gameObject != gameObject)
- {
- Debug.LogErrorFormat("{0}为单例对象,但是场景中存在多个{0},已删除本对象", GetType().Name);
- Destroy(gameObject);
- }
- else
- {
- DeleteSingle = null;
- instance = (T)this;
- InitComplte?.Invoke();
- }
- }
- /// <summary>
- /// 对象被销毁时的事件传递
- /// </summary>
- protected virtual void OnDestroy()
- {
- if (instance == this)
- {
- instance = null;
- DeleteSingle?.Invoke();
- }
- InitComplte = null;
- }
- }
- }
|