CombatEventManager.cs 2.7 KB

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