using System; using System.Collections.Generic; namespace ET { public class BattleEventComponentAwakSystem : AwakeSystem { public override void Awake(BattleEventComponent self) { self.Awake(); } } public class BattleEventComponent : Entity { private static BattleEventComponent instance; private readonly Dictionary> allEvents = new Dictionary>(); /// /// 缓存的结点字典 /// private readonly Dictionary> cachedNodes = new Dictionary>(); /// /// 临时结点字典 /// private readonly Dictionary> tempNodes = new Dictionary>(); public void Awake() { instance = this; } public void RegisterEvent(string eventId, IEvent e) { if (!this.allEvents.ContainsKey(eventId)) { this.allEvents.Add(eventId, new LinkedList()); } this.allEvents[eventId].AddLast(e); } public void UnRegisterEvent(string eventId, IEvent e) { if (cachedNodes.Count > 0) { foreach (KeyValuePair> cachedNode in cachedNodes) { //预防极端情况,比如两个不同的事件id订阅了同一个事件处理者 if (cachedNode.Value != null && cachedNode.Key == eventId && cachedNode.Value.Value == e) { //注意这里添加的Handler是下一个 tempNodes.Add(cachedNode.Key, cachedNode.Value.Next); } } //把临时结点字典中的目标元素值更新到缓存结点字典 if (tempNodes.Count > 0) { foreach (KeyValuePair> cachedNode in tempNodes) { cachedNodes[cachedNode.Key] = cachedNode.Value; } //清除临时结点 tempNodes.Clear(); } } if (this.allEvents.ContainsKey(eventId)) { this.allEvents[eventId].Remove(e); } } public static void Init() { } public static void Publish(string key,T a)where T : struct { instance.PublishInternel(key,a); } private void PublishInternel(string type,T a) where T : struct { if (!this.allEvents.TryGetValue(type, out var iEvents)) { return; } LinkedListNode temp = iEvents.First; while (temp != null) { try { this.cachedNodes[type] = temp.Next; if (!(temp.Value is AEvent_Sync aEvent)) { Log.Error($"event error: {temp.Value.GetType().Name}"); continue; } aEvent.Run(a); } catch (Exception e) { Log.Error(e); } temp = this.cachedNodes[type]; } this.cachedNodes.Remove(type); } } namespace EventType { public struct BuffAdd { public Unit unit; public Unit targetUnit; } } }