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

这个类在写完后,测试的过程中遇到过异常(界面类已经销毁,但回调还能执行的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());
        }
    }
}




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值