c#遊戲事件系統
阿新 • • 發佈:2019-02-14
/// <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>>(); }