EventDispatcher.cs 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108
  1. 
  2. using UnityEngine;
  3. using System.Collections;
  4. using System.Collections.Generic;
  5. using System;
  6. using Newtonsoft.Json.Linq;
  7. /// <summary>
  8. /// 2020.11.30 启用事件分发器
  9. /// </summary>
  10. public class EventDispatcher : MonoSingleton<EventDispatcher>
  11. {
  12. static Dictionary<string, List<Action>> _EventListeners
  13. = new Dictionary<string, List<Action>>();
  14. /// <summary>
  15. /// 注册时间监听
  16. /// </summary>
  17. /// <param name="type"></param>
  18. /// <param name="listener"></param>
  19. public void AddEventListener(string type, Action ac)
  20. {
  21. if (!_EventListeners.ContainsKey(type))
  22. {
  23. _EventListeners.Add(type, new List<Action>());
  24. }
  25. _EventListeners[type].Add(ac);
  26. }
  27. /// <summary>
  28. /// 设置事件监听
  29. /// 注意:当次设定值会覆盖之前所有的注册事件而成为唯一事件
  30. /// </summary>
  31. /// <param name="type"></param>
  32. /// <param name="listener"></param>
  33. public void SetEventListener(string type, Action listener)
  34. {
  35. if (!_EventListeners.ContainsKey(type))
  36. {
  37. _EventListeners.Add(type, new List<Action>());
  38. }
  39. else
  40. {
  41. _EventListeners[type].Clear();
  42. }
  43. _EventListeners[type].Add(listener);
  44. }
  45. /// <summary>
  46. /// 移除事件监听
  47. /// </summary>
  48. /// <param name="type"></param>
  49. /// <param name="listener"></param>
  50. public void RemoveEventListener(string type, Action listener)
  51. {
  52. if (_EventListeners.ContainsKey(type))
  53. {
  54. _EventListeners[type].Remove(listener);
  55. if (_EventListeners[type].Count <= 0)
  56. {
  57. _EventListeners.Remove(type);
  58. }
  59. }
  60. }
  61. /// <summary>
  62. /// 清除特定类型事件监听
  63. /// </summary>
  64. /// <param name="type"></param>
  65. public void RemoveAllEventListener(string type)
  66. {
  67. if (_EventListeners.ContainsKey(type))
  68. {
  69. _EventListeners.Remove(type);
  70. }
  71. }
  72. /// <summary>
  73. /// 清除全部事件监听
  74. /// </summary>
  75. public void ClearAllEventListeners()
  76. {
  77. foreach (string type in _EventListeners.Keys)
  78. {
  79. _EventListeners[type].Clear();
  80. }
  81. _EventListeners.Clear();
  82. }
  83. /// <summary>
  84. /// 发送事件
  85. /// </summary>
  86. /// <param name="type"></param>
  87. /// <param name="_params"></param>
  88. public void DispatchEvent(string type, object _params1 = null, object _params2 = null)
  89. {
  90. if (_EventListeners.ContainsKey(type))
  91. {
  92. foreach (Action ac in _EventListeners[type])
  93. {
  94. if (ac != null)
  95. {
  96. ac();
  97. }
  98. }
  99. }
  100. }
  101. }