using System; using System.Collections; using System.Collections.Generic; /// /// 事件管理器 /// public static class EventManager { private class PostWrapper { public int PostFrame; public int EventID; public IEventMessage Message; public void OnRelease() { PostFrame = 0; EventID = 0; Message = null; } } private static readonly Dictionary>> _listeners = new Dictionary>>(1000); private static readonly List _postWrappers = new List(1000); public static void Update() { for (int i = _postWrappers.Count - 1; i >= 0; i--) { var wrapper = _postWrappers[i]; if (UnityEngine.Time.frameCount > wrapper.PostFrame) { SendMessage(wrapper.EventID, wrapper.Message); _postWrappers.RemoveAt(i); } } } /// /// 添加监听 /// public static void AddListener(System.Action listener) where TEvent : IEventMessage { AddListener(typeof(TEvent), listener); } /// /// 添加监听 /// public static void AddListener(System.Type eventType, System.Action listener) { int eventId = eventType.GetHashCode(); AddListener(eventId, listener); } /// /// 添加监听 /// public static void AddListener(int eventId, System.Action listener) { if (_listeners.ContainsKey(eventId) == false) _listeners.Add(eventId, new List>()); if (_listeners[eventId].Contains(listener) == false) _listeners[eventId].Add(listener); } /// /// 移除监听 /// public static void RemoveListener(System.Action listener) where TEvent : IEventMessage { RemoveListener(typeof(TEvent), listener); } /// /// 移除监听 /// public static void RemoveListener(System.Type eventType, System.Action listener) { int eventId = eventType.GetHashCode(); RemoveListener(eventId, listener); } /// /// 移除监听 /// public static void RemoveListener(int eventId, System.Action listener) { if (_listeners.ContainsKey(eventId)) { if (_listeners[eventId].Contains(listener)) _listeners[eventId].Remove(listener); } } /// /// 实时广播事件 /// public static void SendMessage(IEventMessage message) { int eventId = message.GetType().GetHashCode(); SendMessage(eventId, message); } /// /// 实时广播事件 /// public static void SendMessage(int eventId, IEventMessage message) { if (_listeners.ContainsKey(eventId) == false) return; List> listeners = _listeners[eventId]; for (int i = listeners.Count - 1; i >= 0; i--) { listeners[i].Invoke(message); } } /// /// 延迟广播事件 /// public static void PostMessage(IEventMessage message) { int eventId = message.GetType().GetHashCode(); PostMessage(eventId, message); } /// /// 延迟广播事件 /// public static void PostMessage(int eventId, IEventMessage message) { var wrapper = new PostWrapper(); wrapper.PostFrame = UnityEngine.Time.frameCount; wrapper.EventID = eventId; wrapper.Message = message; _postWrappers.Add(wrapper); } /// /// 清空所有监听 /// public static void ClearListeners() { foreach (int eventId in _listeners.Keys) { _listeners[eventId].Clear(); } _listeners.Clear(); } /// /// 获取监听者总数 /// private static int GetAllListenerCount() { int count = 0; foreach (var list in _listeners) { count += list.Value.Count; } return count; } }