EventGroup.cs 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. using System;
  2. using System.Collections;
  3. using System.Collections.Generic;
  4. namespace UniFramework.Event
  5. {
  6. public class EventGroup
  7. {
  8. private readonly Dictionary<System.Type, List<Action<IEventMessage>>> _cachedListener = new Dictionary<System.Type, List<Action<IEventMessage>>>();
  9. /// <summary>
  10. /// 添加一个监听
  11. /// </summary>
  12. public void AddListener<TEvent>(System.Action<IEventMessage> listener) where TEvent : IEventMessage
  13. {
  14. System.Type eventType = typeof(TEvent);
  15. if (_cachedListener.ContainsKey(eventType) == false)
  16. _cachedListener.Add(eventType, new List<Action<IEventMessage>>());
  17. if (_cachedListener[eventType].Contains(listener) == false)
  18. {
  19. _cachedListener[eventType].Add(listener);
  20. UniEvent.AddListener(eventType, listener);
  21. }
  22. else
  23. {
  24. UniLogger.Warning($"Event listener is exist : {eventType}");
  25. }
  26. }
  27. /// <summary>
  28. /// 移除所有缓存的监听
  29. /// </summary>
  30. public void RemoveAllListener()
  31. {
  32. foreach (var pair in _cachedListener)
  33. {
  34. System.Type eventType = pair.Key;
  35. for (int i = 0; i < pair.Value.Count; i++)
  36. {
  37. UniEvent.RemoveListener(eventType, pair.Value[i]);
  38. }
  39. pair.Value.Clear();
  40. }
  41. _cachedListener.Clear();
  42. }
  43. }
  44. }