EventManager.cs 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  1. // #if !COMBAT_SERVER
  2. using System;
  3. using System.Collections.Generic;
  4. using Utility;
  5. namespace Fort23.Core
  6. {
  7. #if !COMBAT_SERVER
  8. /// <summary>
  9. /// 事件调度器
  10. /// </summary>
  11. public class EventManager : Singleton<EventManager>
  12. {
  13. public delegate void CustomEventHandler(IEventData e);
  14. private readonly Dictionary<CustomEventType, CustomEventHandler> _eventHandlers;
  15. public EventManager()
  16. {
  17. _eventHandlers = new Dictionary<CustomEventType, CustomEventHandler>();
  18. }
  19. /// <summary>
  20. /// 注册事件,没有处理重复,需要注意
  21. /// </summary>
  22. /// <param name="type"></param>
  23. /// <param name="handle"></param>
  24. public void AddEventListener(CustomEventType type, CustomEventHandler handle)
  25. {
  26. if (!_eventHandlers.ContainsKey(type))
  27. {
  28. _eventHandlers.Add(type, handle);
  29. }
  30. else
  31. {
  32. _eventHandlers[type] -= handle;
  33. _eventHandlers[type] += handle;
  34. }
  35. }
  36. /// <summary>
  37. /// 取消注册
  38. /// </summary>
  39. /// <param name="type"></param>
  40. /// <param name="handle"></param>
  41. public void RemoveEventListener(CustomEventType type, CustomEventHandler handle)
  42. {
  43. if (_eventHandlers.ContainsKey(type))
  44. {
  45. _eventHandlers[type] -= handle;
  46. }
  47. }
  48. /// <summary>
  49. /// 取消注册所有当前类型的事件
  50. /// </summary>
  51. /// <param name="type"></param>
  52. public void RemoveAllEventListener(CustomEventType type)
  53. {
  54. if (_eventHandlers.ContainsKey(type))
  55. {
  56. _eventHandlers.Remove(type);
  57. }
  58. }
  59. // ReSharper restore Unity.ExpensiveCode
  60. /// <summary>
  61. /// 事件触发执行的方法,Public方便外界调用,谁执行,谁给执行细节
  62. /// </summary>
  63. public void Dispatch(CustomEventType type, IEventData eventData, bool isRecycle = true)
  64. {
  65. if (_eventHandlers.ContainsKey(type))
  66. {
  67. if (_eventHandlers[type] != null)
  68. {
  69. _eventHandlers[type](eventData);
  70. }
  71. }
  72. if (isRecycle && eventData != null)
  73. {
  74. eventData?.Recycle();
  75. }
  76. }
  77. }
  78. #endif
  79. }
  80. // #endif