UnitySingleton.cs 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  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. /// 注意,尽量避免在多处使用或者在awake中使用,避免产生多个实例化多项
  38. /// </summary>
  39. public static T ForceInstance()
  40. {
  41. if (!instance)
  42. {
  43. GameObject obj = new GameObject();
  44. instance= obj.AddComponent<T>();
  45. }
  46. return instance;
  47. }
  48. /// <summary>
  49. /// Base awake method that sets the singleton's unique instance.
  50. /// </summary>
  51. protected virtual void Awake()
  52. {
  53. if (instance != null && instance.gameObject != gameObject)
  54. {
  55. Debug.LogErrorFormat("{0}为单例对象,但是场景中存在多个{0},已删除本对象", GetType().Name);
  56. Destroy(gameObject);
  57. }
  58. else
  59. {
  60. DeleteSingle = null;
  61. instance = (T)this;
  62. InitComplte?.Invoke();
  63. }
  64. }
  65. /// <summary>
  66. /// 对象被销毁时的事件传递
  67. /// </summary>
  68. protected virtual void OnDestroy()
  69. {
  70. if (instance == this)
  71. {
  72. instance = null;
  73. DeleteSingle?.Invoke();
  74. }
  75. InitComplte = null;
  76. }
  77. }
  78. }