Unity自定义事件(自定义回调函数参数个数)

首先实现的功能很简单,就是点击按钮,文本显示(内心吐槽:这么简单还自定义干嘛啊!!!当然是为了学习QAQ) 

 第一步:创建一个枚举类型(测试就写一个类型了)

public enum EventType
{
    eventText
}

第二步:创建delegate类(用做泛型)

public delegate void EventCallBack();
public delegate void EventCallBack<T>(T arg1);
public delegate void EventCallBack<T,W>(T arg1,W arg2);
public delegate void EventCallBack<T,W,E>(T arg1, W arg2, E arg3);
public delegate void EventCallBack<T,W,E,R>(T arg1, W arg2, E arg3, R arg4);
public delegate void EventCallBack<T, W, E, R,Y>(T arg1, W arg2, E arg3, R arg4, Y arg5);

第三步(重点来了):定义一个事件中心,用来添加消息,移除消息,广播消息

public class EventCenten
{
    private static Dictionary<EventType, Delegate> m_EventTable = new Dictionary<EventType, Delegate>();

    //提取相同的代码段,使用Delegate就可以让方法通用(无论函数是否带参)
    static void AddingListen(EventType eventType, Delegate callBack)
    {
        //如果类型已经存在(键相等)
        if (!m_EventTable.ContainsKey(eventType))
        {
            m_EventTable.Add(eventType, null);
        }
        //获取该回掉函数
        Delegate d = m_EventTable[eventType];
        //判断委托对象(函数)是不是空值,类型是否一致(带一个参,还是两个或者更多)
        if (d != null && d.GetType() != callBack.GetType())
        {
            throw new Exception(string.Format("尝试为事件{0}添加不同类型的委托,当前事件所对应的委托是{1},要添加的委托是{2}", eventType, d.GetType(), callBack.GetType()));
        }
    }


    static void RemovingListen(EventType eventType, Delegate callBack)
    {
        if (m_EventTable.ContainsKey(eventType))
        {
            Delegate d = m_EventTable[eventType];
            if (d == null)
            {
                throw new Exception(string.Format("移除监听错误:事件{0}没有对应的委托", eventType));
            }
            else if (d.GetType() != callBack.GetType())
            {
                throw new Exception(string.Format("移除监听错误:尝试为事件{0}移除不同的类型的委托,当前委托类型为{1},要移除的对象
  • 3
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值