您的位置:首页 > 移动开发 > Unity3D

Unity事件管理类,用于不同对象之间传递消息

2017-03-11 14:19 204 查看
这个类在写完后,测试的过程中遇到过异常(界面类已经销毁,但回调还能执行的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());
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐