驱蚊app
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 

45 line
1.1 KiB

  1. using System;
  2. using System.Collections.Generic;
  3. using UnityEngine;
  4. public static class EventCenter
  5. {
  6. // 使用 enum 作为事件名的 key
  7. private static Dictionary<EventType, Action<object>> eventDict = new Dictionary<EventType, Action<object>>();
  8. /// 添加监听器
  9. public static void AddListener(EventType eventType, Action<object> callback)
  10. {
  11. if (eventDict.ContainsKey(eventType))
  12. eventDict[eventType] += callback;
  13. else
  14. eventDict[eventType] = callback;
  15. }
  16. /// 移除监听器
  17. public static void RemoveListener(EventType eventType, Action<object> callback)
  18. {
  19. if (eventDict.ContainsKey(eventType))
  20. {
  21. eventDict[eventType] -= callback;
  22. if (eventDict[eventType] == null)
  23. eventDict.Remove(eventType);
  24. }
  25. }
  26. /// 触发事件
  27. public static void Trigger(EventType eventType, object param = null)
  28. {
  29. if (eventDict.TryGetValue(eventType, out var callback))
  30. {
  31. callback?.Invoke(param);
  32. }
  33. }
  34. /// 清空所有监听
  35. public static void Clear()
  36. {
  37. eventDict.Clear();
  38. }
  39. }