Unity 框架

EventManager.cs 2.1KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. using System;
  2. using System.Collections;
  3. using System.Collections.Generic;
  4. using UnityEngine;
  5. namespace TFramework
  6. {
  7. /// <summary>
  8. /// 事件管理器
  9. /// </summary>
  10. public class EventManager:BaseManager
  11. {
  12. private Dictionary<string, TAction> _events = new Dictionary<string, TAction>();
  13. private Dictionary<Type, TAction<EventBase>> events = new Dictionary<Type, TAction<EventBase>>();
  14. /// <summary>
  15. /// 注册事件
  16. /// </summary>
  17. /// <param name="type">事件类型</param>
  18. /// <param name="action">事件</param>
  19. public void RegistEvent(Type type, TAction<EventBase> action)
  20. {
  21. if (events.ContainsKey(type))
  22. events[type] += action;
  23. else
  24. events.Add(type, action);
  25. }
  26. /// <summary>
  27. /// 注册事件
  28. /// </summary>
  29. /// <param name="T">事件类型</param>
  30. /// <param name="action">事件</param>
  31. public void RegistEvent<T>(TAction<EventBase> action) => RegistEvent(typeof(T), action);
  32. /// <summary>
  33. /// 派发事件
  34. /// </summary>
  35. /// <param name="eventBase">事件数据</param>
  36. public void DispatchEvent(Type type, EventBase eventBase)=> events.TryGet(type)?.Invoke(eventBase);
  37. /// <summary>
  38. /// 派发事件
  39. /// </summary>
  40. /// <param name="T">事件类型</param>
  41. public void DispatchEvent<T>(EventBase eventBase) => events.TryGet(typeof(T))?.Invoke(eventBase);
  42. /// <summary>
  43. /// 注销事件
  44. /// </summary>
  45. /// <typeparam name="type">事件类型</typeparam>
  46. /// <param name="eventBase">事件</param>
  47. public void UnRegist(Type type,TAction<EventBase> action)
  48. {
  49. if (events.ContainsKey(type))
  50. events[type] -= action;
  51. }
  52. /// <summary>
  53. /// 注销事件
  54. /// </summary>
  55. /// <param name="T">事件类型</param>
  56. public void UnRegis<T>(TAction<EventBase> action) => UnRegist(typeof(T), action);
  57. }
  58. }