Unity事件中心(基于委托实现)

Unity事件中心

为什么要运用事件中心

降低程序耦合性,减小程序复杂度
在这里插入图片描述

举个例子

老师发布了一个问题,但是老师要是每个人去询问就会花费大量的时间,十分不方便,要是同学们能在老师发布问题后主动告知老师,那就很方便了。
在这里插入图片描述

如何在Unity中实现

首先我们创建3个脚本CallBack(事件回调)EventCenter(事件管理的中心)EventType(事件的标签)

在这里插入图片描述

CallBack

根据需要定义多个不同参数的委托
在这里插入图片描述

EventCenter

首先定义一个字典来存储

    private static Dictionary<EventType,Delegate> m_dic=new Dictionary<EventType, Delegate>();

EventType通过枚举来存放方法标签(这里的方法标签为了一会儿测试使用,可以忽略)
在这里插入图片描述

事件中心需要对应的3个方法
1.添加监听
2.移除监听
3.广播事件

1.添加监听
在这里插入图片描述
2.移除监听
在这里插入图片描述
3.广播事件
在这里插入图片描述
这样简单的事件中心就实现完成了
下面是事件中心的完整代码

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System;

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

    public static void AddListen(EventType eventType,CallBack callBack)
    {
        if (!m_dic.ContainsKey(eventType))
        {
            m_dic.Add(eventType,null);
        }

        Delegate d = m_dic[eventType];
        if (d!=null&& d.GetType()!=callBack.GetType())
        {
            throw new Exception("类型不同");
        }

        m_dic[eventType] = (CallBack) m_dic[eventType] + callBack;
    }

    public static void RemoveListen(EventType eventType, CallBack callBack)
    {
        if (m_dic.ContainsKey(eventType))
        {
            Delegate d = m_dic[eventType];
            if (d==null)
            {
                throw new Exception("没有对应的事件");
            }
            else if (d.GetType()!=callBack.GetType())
            {
                throw new Exception("类型不同");
            }
        }
        else
        {
            throw new Exception("没有对应的事件");
        }

        m_dic[eventType] = (CallBack) m_dic[eventType] - callBack;
    }

    public static void Broadcast(EventType eventType)
    {
        Delegate d;
        if (m_dic.TryGetValue(eventType,out d))
        {
            CallBack callBack = (CallBack) d;
            if (callBack!=null)
            {
                callBack();
            }
            else
            {
                throw new Exception("CallBack为空");
            }
        }
    }
}

下面进行测试

当按下按钮就让文字现实出来
在这里插入图片描述
这两个测试脚本中的代码
在这里插入图片描述
在这里插入图片描述
当点击按钮时文本就显示出来了

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值