2025-05-09 15:40:34 +08:00

146 lines
3.7 KiB
C#

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