using System; using System.Collections.Generic; using PhxhSDK; namespace Framework { public partial class EventManager : Singlenton { private Dictionary> _eventDict = new Dictionary>(); private Action _afterSendCallBack; public event Action AfterSendCallBack { add => _afterSendCallBack += value; remove => _afterSendCallBack -= value; } public const int MAX_EVENT_STACK = 3; public void Register(EventName eventName, Action action) { try { if (action == null) { return; } if (!_eventDict.ContainsKey(eventName)) { _eventDict[eventName] = new HashSet(); } _eventDict[eventName].Add(action); } catch (Exception e) { DebugUtil.LogError("EventSystem.Register : {0}, {1}", eventName, e); } } public void Register(EventName eventName, Action action) { try { if (action == null) { return; } if (!_eventDict.ContainsKey(eventName)) { _eventDict[eventName] = new HashSet(); } _eventDict[eventName].Add(action); } catch (Exception e) { DebugUtil.LogError("EventSystem.Register : {0}, {1}", eventName, e); } } public void Unregister(EventName eventName, Action action) { try { if (action == null) { return; } if (!_eventDict.ContainsKey(eventName)) { return; } _eventDict[eventName].Remove(action); } catch (Exception e) { DebugUtil.LogError("EventSystem.Unregister : {0}, {1}", eventName, e); } } public void Unregister(EventName eventName, Action action) { try { if (action == null) { return; } if (!_eventDict.ContainsKey(eventName)) { return; } _eventDict[eventName].Remove(action); } catch (Exception e) { DebugUtil.LogError("EventSystem.Unregister : {0}, {1}", eventName, e); } } public void Send(EventName eventName, T arg) { try { if (EventStackReachMax(++_eventStack)) { DebugUtil.LogError("EventSystem.Send : {0}, {1}", eventName, arg); return; } //DebugUtil.Log($"EventSystem.Send : {eventName}"); if (!_eventDict.ContainsKey(eventName)) { _eventStack--; _afterSendCallBack?.Invoke(eventName); return; } var actions = _eventDict[eventName]; var tempExecuteList = GetTempExecuteList(); tempExecuteList.AddRange(actions); using var e = tempExecuteList.GetEnumerator(); while (e.MoveNext()) { if (e.Current is Action actionT) { actionT(arg); } } ReCycleTempExecuteList(tempExecuteList); _afterSendCallBack?.Invoke(eventName); _eventStack--; } catch (Exception exception) { DebugUtil.LogError("EventSystem.Send : {0}, {1}", eventName, exception); } } public void Send(EventName eventName) { try { if (!_eventDict.ContainsKey(eventName)) { _afterSendCallBack?.Invoke(eventName); return; } var actions = _eventDict[eventName]; foreach (var action in actions) { if (action is Action actionT) { actionT(); } } _afterSendCallBack?.Invoke(eventName); } catch (Exception e) { DebugUtil.LogError("EventSystem.Send : {0}, {1}", eventName, e); } } private bool EventStackReachMax(int current) { if (current > MAX_EVENT_STACK) { DebugUtil.EditorAssert(_eventStack <= MAX_EVENT_STACK, $"EventSystem.Send : {MAX_EVENT_STACK}"); return true; } return false; } } }