using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System;
public delegate void EventHandle(params object[] args);
public delegate void EventHandle<T>(T e, params object[] args);
public class GlobalEvent
{
//以Enum为Key的事件派发
private static Dictionary<Enum, EventHandle> mEventDic = new Dictionary<Enum, EventHandle>();
private static Dictionary<Enum, List<EventHandle>> mUseOnceEventDic = new Dictionary<Enum, List<EventHandle>>();
//添加事件及回调
public static void AddEvent(Enum type, EventHandle handle, bool isUseOnce = false)
{
if (isUseOnce)
{
if (mUseOnceEventDic.ContainsKey(type))
{
if (!mUseOnceEventDic[type].Contains(handle))
mUseOnceEventDic[type].Add(handle);
else
Debug.LogWarning("already existing EventType: " + type + " handle: " + handle);
}
else
{
List<EventHandle> temp = new List<EventHandle>();
temp.Add(handle);
mUseOnceEventDic.Add(type, temp);
}
}
else
{
if (mEventDic.ContainsKey(type))
{
mEventDic[type] += handle;
}
else
{
mEventDic.Add(type, handle);
}
}
}
//移除某类事件的一个回调
public static void RemoveEvent(Enum type, EventHandle handle)
{
if (mUseOnceEventDic.ContainsKey(type))
{
if (mUseOnceEventDic[type].Contains(handle))
{
mUseOnceEventDic[type].Remove(handle);
if (mUseOnceEventDic[type].Count == 0)
{
mUseOnceEventDic.Remove(type);
}
}
}
if (mEventDic.ContainsKey(type))
{
mEventDic[type] -= handle;
}
}
//移除某类事件
public static void RemoveEvent(Enum type)
{
if (mUseOnceEventDic.ContainsKey(type))
{
mUseOnceEventDic.Remove(type);
}
if (mEventDic.ContainsKey(type))
{
mEventDic.Remove(type);
}
}
//触发事件
public static void DispatchEvent(Enum type, params object[] args)
{
if (mEventDic.ContainsKey(type))
{
try
{
if (mEventDic[type] != null)
{
mEventDic[type](args);
}
}
catch (Exception e)
{
Debug.LogError(e.ToString());
}
}
if (mUseOnceEventDic.ContainsKey(type))
{
for (int i = 0; i < mUseOnceEventDic[type].Count; i++)
{
foreach (EventHandle callBack in mUseOnceEventDic[type][i].GetInvocationList())
{
try
{
callBack(args);
}
catch (Exception e)
{
Debug.LogError(e.ToString());
}
}
}
RemoveEvent(type);
}
}
}