AssetBase/Assets/EventManager/Scripts/EventManager.cs

66 lines
2.1 KiB
C#
Raw Normal View History

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;
if (tempDelegate == null)
{
_delegateDict.Remove(type);
_delegateLookupDict.Remove(callback);
}
else
{
_delegateDict[type] = tempDelegate;
}
}
}
}
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();
}
}
}