using FirstVillain.Singleton; using System; using System.Collections.Generic; namespace FirstVillain.Event { public class EventManager : UnitySingleton { public delegate void EventDelegate(T cEvent) where T : CommonEventBase; private delegate void EventDelegate(CommonEventBase cEvent); private Dictionary _delegateDict = new(); private Dictionary _delegateLookupDict = new(); private void AddListener(EventDelegate callback) where T : CommonEventBase { EventDelegate newDelegate = e => callback(e as T); _delegateLookupDict[callback] = newDelegate; var type = typeof(T); if (!_delegateDict.TryGetValue(type, out EventDelegate tempDeletage)) { _delegateDict[type] = tempDeletage; } _delegateDict[type] += newDelegate; } public void DelListener(EventDelegate callback) where T : CommonEventBase { if (_delegateLookupDict.TryGetValue(callback, out EventDelegate targetDelegate)) { var type = typeof(T); if (_delegateDict.TryGetValue(type, out EventDelegate tempDelegate)) { tempDelegate -= targetDelegate; if (tempDelegate == null) { _delegateDict.Remove(type); } else { _delegateDict[type] = tempDelegate; } } _delegateLookupDict.Remove(callback); } } public static void ExecuteEvent(CommonEventBase cEvent) { if (Instance._delegateDict.TryGetValue(cEvent.GetType(), out EventDelegate callback)) { callback.Invoke(cEvent); } } public void Clear() { _delegateDict.Clear(); _delegateLookupDict.Clear(); } } }