You cannot select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
66 lines
2.1 KiB
C#
66 lines
2.1 KiB
C#
using System;
|
|
using System.Collections.Generic;
|
|
using LanLib.Singleton;
|
|
using UnityEngine;
|
|
|
|
namespace LanLib.EventManager
|
|
{
|
|
public sealed class EventManager : Singleton<EventManager>, IEventManager
|
|
{
|
|
private readonly Dictionary<Type, Delegate> _eventDictionary = new();
|
|
public void Subscribe<T>(Action<T> 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<T>(Action<T> 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>(T eventInstance) where T : struct
|
|
{
|
|
var eventId = typeof(T);
|
|
if (!_eventDictionary.ContainsKey(eventId)) return;
|
|
|
|
foreach (var listener in _eventDictionary[eventId].GetInvocationList())
|
|
{
|
|
try
|
|
{
|
|
((Action<T>)listener)?.Invoke(eventInstance);
|
|
}
|
|
catch (Exception exception)
|
|
{
|
|
#if UNITY_EDITOR || DEVELOPMENT_BUILD
|
|
Debug.LogError(ErrorMessages.EventListenerTriggerException(eventId, exception));
|
|
#endif
|
|
}
|
|
}
|
|
}
|
|
|
|
public void ClearEvent<T>() where T : struct
|
|
{
|
|
var eventId = typeof(T);
|
|
_eventDictionary.Remove(eventId);
|
|
}
|
|
|
|
public void ClearAllEvents() => _eventDictionary.Clear();
|
|
}
|
|
} |