UnitySingleton.cs 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. // Copyright (c) Microsoft Corporation. All rights reserved.
  2. // Licensed under the MIT License. See LICENSE in the project root for license information.
  3. using System;
  4. using UnityEngine;
  5. namespace XRTool.Util
  6. {
  7. /// <summary>
  8. /// Unity的单例
  9. /// Singleton behaviour class, used for components that should only have one instance
  10. ///
  11. /// </summary>
  12. /// <typeparam name="T"></typeparam>
  13. public abstract class UnitySingleton<T> : MonoBehaviour where T : UnitySingleton<T>
  14. {
  15. public static event Action InitComplte;
  16. public static event Action DeleteSingle;
  17. private static T instance;
  18. public static T Instance
  19. {
  20. get
  21. {
  22. return instance;
  23. }
  24. }
  25. /// <summary>
  26. /// Returns whether the instance has been initialized or not.
  27. /// </summary>
  28. public static bool IsInitialized
  29. {
  30. get
  31. {
  32. return instance != null;
  33. }
  34. }
  35. /// <summary>
  36. /// 强制实例化某对象
  37. /// 注意此操作不是同步完成的
  38. /// </summary>
  39. public static void ForceInstance()
  40. {
  41. if (!instance)
  42. {
  43. GameObject obj = new GameObject();
  44. obj.AddComponent<T>();
  45. }
  46. }
  47. /// <summary>
  48. /// Base awake method that sets the singleton's unique instance.
  49. /// </summary>
  50. protected virtual void Awake()
  51. {
  52. if (instance != null && instance.gameObject != gameObject)
  53. {
  54. Debug.LogErrorFormat("{0}为单例对象,但是场景中存在多个{0},已删除本对象", GetType().Name);
  55. Destroy(gameObject);
  56. }
  57. else
  58. {
  59. DeleteSingle = null;
  60. instance = (T)this;
  61. InitComplte?.Invoke();
  62. }
  63. }
  64. /// <summary>
  65. /// 对象被销毁时的事件传递
  66. /// </summary>
  67. protected virtual void OnDestroy()
  68. {
  69. if (instance == this)
  70. {
  71. instance = null;
  72. DeleteSingle?.Invoke();
  73. }
  74. InitComplte = null;
  75. }
  76. }
  77. }