using System; using System.Collections.Generic; using UnityEngine; /// /// 游戏事件系统 - 静态类 /// 提供添加监听、发送事件和移除监听的功能 /// public static class GameEvent { // 使用字典存储事件名称和对应的监听器列表 private static Dictionary>> eventDictionary = new Dictionary>>(); /// /// 添加事件监听 /// /// 事件名称 /// 事件监听器 public static void AddListener(string eventName, Action listener) { // 检查事件名称是否为空 if (string.IsNullOrEmpty(eventName)) { Debug.LogError("GameEvent: 事件名称不能为空!"); return; } // 检查监听器是否为空 if (listener == null) { Debug.LogError("GameEvent: 监听器不能为空!"); return; } // 如果事件不存在,创建新的监听器列表 if (!eventDictionary.ContainsKey(eventName)) { eventDictionary[eventName] = new List>(); } // 添加监听器到列表中 eventDictionary[eventName].Add(listener); } /// /// 发送事件 /// /// 事件名称 /// 事件参数 public static void Send(string eventName, object param = null) { // 检查事件名称是否为空 if (string.IsNullOrEmpty(eventName)) { Debug.LogError("GameEvent: 事件名称不能为空!"); return; } // 如果事件不存在,直接返回 if (!eventDictionary.ContainsKey(eventName)) { return; } // 获取监听器列表 List> listeners = eventDictionary[eventName]; // 调用所有监听器 for (int i = 0; i < listeners.Count; i++) { try { listeners[i].Invoke(param); } catch (Exception e) { Debug.LogError($"GameEvent: 执行事件 '{eventName}' 的监听器时发生异常: {e.Message}"); } } } /// /// 移除事件监听 /// /// 事件名称 /// 事件监听器 public static void RemoveListener(string eventName, Action listener) { // 检查事件名称是否为空 if (string.IsNullOrEmpty(eventName)) { Debug.LogError("GameEvent: 事件名称不能为空!"); return; } // 检查监听器是否为空 if (listener == null) { Debug.LogError("GameEvent: 监听器不能为空!"); return; } // 如果事件不存在,直接返回 if (!eventDictionary.ContainsKey(eventName)) { return; } // 从列表中移除监听器 eventDictionary[eventName].Remove(listener); // 如果监听器列表为空,移除事件 if (eventDictionary[eventName].Count == 0) { eventDictionary.Remove(eventName); } } /// /// 清除所有事件监听 /// public static void ClearAllEvents() { eventDictionary.Clear(); } /// /// 清除指定事件的所有监听 /// /// 事件名称 public static void ClearEvent(string eventName) { // 检查事件名称是否为空 if (string.IsNullOrEmpty(eventName)) { Debug.LogError("GameEvent: 事件名称不能为空!"); return; } // 如果事件存在,移除整个事件 if (eventDictionary.ContainsKey(eventName)) { eventDictionary.Remove(eventName); } } }