这个类在写完后,测试的过程中遇到过异常(界面类已经销毁,但回调还能执行的BUG!)。
当然后面修复了,就是“if“后面一串“||”。
这个类可以再扩展一点,不使用字符串做键值。
using System;
using System.Collections.Generic;
// Editor: 760736077@qq.com
public delegate void UIEventFun(object param);
public class UIEventManager : Singleton<UIEventManager> {
Dictionary<string, List<UIEventFun>> dic = new Dictionary<string, List<UIEventFun>>();
public void Register(string key, UIEventFun fun)
{
if(dic.ContainsKey(key))
{
dic[key].Add(fun);
}
else
{
List<UIEventFun> lstFun = new List<UIEventFun>();
lstFun.Add(fun);
dic[key] = lstFun;
}
}
public void UnRegister(string key, UIEventFun fun)
{
if(dic.ContainsKey(key))
{
dic[key].Remove(fun);
if (dic[key].Count == 0)
{
dic.Remove(key);
}
}
}
public void Dispatch(string key, object param)
{
try
{
if (dic.ContainsKey(key))
{
for (int i = dic[key].Count - 1; i >= 0; --i)
{
if (dic[key][i] == null || dic[key][i].Target == null || ((dic[key][i].Target is UnityEngine.Object) && dic[key][i].Target.Equals(null)))
{
dic[key].RemoveAt(i);
continue;
}
dic[key][i](param);
}
}
}
catch (Exception e)
{
uLog.LogError(uLog.uException, "Event Error: " + e.ToString());
}
}
}