using System.Collections.Generic; using System; using UnityEngine; namespace Tuan.GameFramework { public static class EventBus { private static readonly Dictionary _eventHandlers = new Dictionary(); private static readonly object _lock = new object(); public static void Register(IEventHandler handler) where TEvent : IEvent { lock (_lock) { Type eventType = typeof(TEvent); if (!_eventHandlers.ContainsKey(eventType)) { _eventHandlers[eventType] = new List>(); } var handlers = _eventHandlers[eventType] as List>; if (handler != null && !handlers.Contains(handler)) { handlers.Add(handler); } } } public static void Unregister(IEventHandler handler) where TEvent : IEvent { lock (_lock) { Type eventType = typeof(TEvent); if (_eventHandlers.ContainsKey(eventType)) { var handlers = _eventHandlers[eventType] as List>; handlers?.Remove(handler); if (handlers != null && handlers.Count == 0) { _eventHandlers.Remove(eventType); } } } } public static void Publish(TEvent eventData) where TEvent : IEvent { List> handlersToInvoke = null; lock (_lock) { Type eventType = typeof(TEvent); if (_eventHandlers.ContainsKey(eventType)) { var handlers = _eventHandlers[eventType] as List>; if (handlers != null && handlers.Count > 0) { handlersToInvoke = new List>(handlers); } } } // 在锁外执行事件处理,避免死锁 if (handlersToInvoke != null) { foreach (var handler in handlersToInvoke) { try { handler?.HandleEvent(eventData); } catch (Exception e) { Debug.LogError($"Event handling error in {handler.GetType().Name}: {e}"); } } } } public static void Clear() { lock (_lock) { _eventHandlers.Clear(); } } } }