using System; using System.Collections.Generic; using LanLib.Singleton; using UnityEngine; namespace LanLib.EventManager { public sealed class EventManager : Singleton, IEventManager { private readonly Dictionary _eventDictionary = new(); public void Subscribe(Action listener) where T : struct { var eventId = typeof(T); if (listener is null) { #if UNITY_EDITOR || DEVELOPMENT_BUILD Debug.LogError(ErrorMessages.NullListenerSubscribed(eventId)); return; #endif } if (_eventDictionary.ContainsKey(eventId)) { _eventDictionary[eventId] = Delegate.Combine(_eventDictionary[eventId], listener); return; } _eventDictionary[eventId] = listener; } public void Unsubscribe(Action listener) where T : struct { var eventId = typeof(T); if (!_eventDictionary.ContainsKey(eventId)) return; _eventDictionary[eventId] = Delegate.Remove(_eventDictionary[eventId], listener); if (_eventDictionary[eventId] is null) _eventDictionary.Remove(eventId); } public void TriggerEvent(T eventInstance) where T : struct { var eventId = typeof(T); if (!_eventDictionary.ContainsKey(eventId)) return; foreach (var listener in _eventDictionary[eventId].GetInvocationList()) { try { ((Action)listener)?.Invoke(eventInstance); } catch (Exception exception) { #if UNITY_EDITOR || DEVELOPMENT_BUILD Debug.LogError(ErrorMessages.EventListenerTriggerException(eventId, exception)); #endif } } } public void ClearEvent() where T : struct { var eventId = typeof(T); _eventDictionary.Remove(eventId); } public void ClearAllEvents() => _eventDictionary.Clear(); } }