/// <summary>
/// 游戏事件分发器,用于监听、广播游戏事件。
/// </summary>
public static class EventDispatcher
{
public delegate void EventListener(Dictionary<string, object> args);
/// <summary>
/// 广播指定事件。
/// </summary>
/// <param name="eventId">事件编号</param>
/// <param name="args">事件参数</param>
public static void Dispatch(int eventId, Dictionary<string, object> args = null)
{
var luaListeners = getLuaEventListener(eventId);
for (var i = 0; i < luaListeners.Count; i++)
{
var listener = luaListeners[i];
listener.Function.Call(listener.Self, args);
}
var listeners = getEventListeners(eventId);
for (var i = 0; i < listeners.Count; i++)
listeners[i].Invoke(args);
}
/// <summary>
/// 添加对指定事件的监听。
/// </summary>
/// <param name="eventId">事件编号</param>
/// <param name="listener">回调委托</param>
[NoToLua]
public static void AddListener(int eventId, EventListener listener)
{
var listeners = getEventListeners(eventId);
listeners.Add(listener);
}
/// <summary>
/// 移除对指定事件的监听。
/// </summary>
/// <param name="eventId">事件编号</param>
/// <param name="listenerToBeRemoved">回调委托</param>
[NoToLua]
public static void RemoveListener(int eventId, EventListener listenerToBeRemoved)
{
var listeners = getEventListeners(eventId);
for (var i = 0; i < listeners.Count; i++)
{
var listener = listeners[i];
if (listener == listenerToBeRemoved)
{
listeners.RemoveAt(i);
break;
}
}
}
/// <summary>
/// 清除所有的事件监听器。
/// </summary>
public static void Clear()
{
_listeners.Clear();
_luaListeners.Clear();
}
private static List<EventListener> getEventListeners(int eventId)
{
List<EventListener> ret;
if (_listeners.TryGetValue(eventId, out ret))
return ret;
ret = new List<EventListener>();
_listeners.Add(eventId, ret);
return ret;
}
private static readonly Dictionary<int, List<EventListener>> _listeners = new Dictionary<int, List<EventListener>>();
}
c#游戏事件系统
最新推荐文章于 2022-01-24 17:50:21 发布