UnitySingleton.cs 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  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. try
  23. {
  24. return instance;
  25. }
  26. catch
  27. {
  28. return null;
  29. }
  30. }
  31. }
  32. /// <summary>
  33. /// Returns whether the instance has been initialized or not.
  34. /// </summary>
  35. public static bool IsInitialized
  36. {
  37. get
  38. {
  39. return instance != null;
  40. }
  41. }
  42. /// <summary>
  43. /// 强制实例化某对象
  44. /// 注意,尽量避免在多处使用或者在awake中使用,避免产生多个实例化多项
  45. /// </summary>
  46. public static T ForceInstance()
  47. {
  48. if (!instance)
  49. {
  50. GameObject obj = new GameObject();
  51. instance= obj.AddComponent<T>();
  52. }
  53. return instance;
  54. }
  55. /// <summary>
  56. /// Base awake method that sets the singleton's unique instance.
  57. /// </summary>
  58. protected virtual void Awake()
  59. {
  60. if (instance != null && instance.gameObject != gameObject)
  61. {
  62. Debug.LogErrorFormat("{0}为单例对象,但是场景中存在多个{0},已删除本对象", GetType().Name);
  63. Destroy(gameObject);
  64. }
  65. else
  66. {
  67. DeleteSingle = null;
  68. instance = (T)this;
  69. InitComplte?.Invoke();
  70. }
  71. }
  72. /// <summary>
  73. /// 对象被销毁时的事件传递
  74. /// </summary>
  75. protected virtual void OnDestroy()
  76. {
  77. if (instance == this)
  78. {
  79. instance = null;
  80. DeleteSingle?.Invoke();
  81. }
  82. InitComplte = null;
  83. }
  84. }
  85. }