2023-08-16 18:50:41 +09:00
|
|
|
using FirstVillain.Singleton;
|
|
|
|
using System;
|
|
|
|
using System.Collections.Generic;
|
|
|
|
|
|
|
|
namespace FirstVillain.Event
|
|
|
|
{
|
|
|
|
public class EventManager : UnitySingleton<EventManager>
|
|
|
|
{
|
|
|
|
public delegate void EventDelegate<T>(T cEvent) where T : CommonEventBase;
|
|
|
|
private delegate void EventDelegate(CommonEventBase cEvent);
|
|
|
|
|
|
|
|
private Dictionary<Type, EventDelegate> _delegateDict = new();
|
|
|
|
private Dictionary<Delegate, EventDelegate> _delegateLookupDict = new();
|
|
|
|
|
|
|
|
private void AddListener<T>(EventDelegate<T> 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<T>(EventDelegate<T> callback) where T : CommonEventBase
|
|
|
|
{
|
|
|
|
if (_delegateLookupDict.TryGetValue(callback, out EventDelegate targetDelegate))
|
|
|
|
{
|
|
|
|
var type = typeof(T);
|
|
|
|
if (_delegateDict.TryGetValue(type, out EventDelegate tempDelegate))
|
|
|
|
{
|
|
|
|
tempDelegate -= targetDelegate;
|
2023-08-16 19:44:41 +09:00
|
|
|
if (tempDelegate == null)
|
2023-08-16 18:50:41 +09:00
|
|
|
{
|
|
|
|
_delegateDict.Remove(type);
|
|
|
|
}
|
|
|
|
else
|
|
|
|
{
|
|
|
|
_delegateDict[type] = tempDelegate;
|
|
|
|
}
|
|
|
|
}
|
2023-08-16 19:28:41 +09:00
|
|
|
|
|
|
|
_delegateLookupDict.Remove(callback);
|
2023-08-16 18:50:41 +09:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
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();
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|