Unity原生的事件监听与广播系统——UnityEvent

提示:文章写完后,目录可以自动生成,如何生成可参考右边的帮助文档

Unity原生的事件监听与广播系统——UnityEvent


前言

我们在开发Unity程序的过程中会用到事件系统,除了自己开发一套监听与广播系统,也可以使用Unity中原生的监听与广播系统——UnityEvent
Unity官方文档地址:https://docs.unity3d.com/cn/2019.4/ScriptReference/Events.UnityEvent.html


一、示例代码

首先要定义所有的事件,可以写一个事件类
Events.cs

using UnityEngine.Events;

[System.Serializable]
public class Events
{
    public UnityEvent zeroParaEvent;
    public UnityEvent<int> oneParaEvent;
    public UnityEvent<int, string> twoParaEvent;
    public UnityEvent<int, string, float> threeParaEvent;
}

然后是事件广播类,在这里触发相应的广播事件

Menu.cs

using UnityEngine;
using UnityEngine.UI;

public class Menu : MonoBehaviour
{
    public Button zeroBt;
    public Button oneBt;
    public Button twoBt;
    public Button threeBt;

    public Events events;

    private void Start()
    {
        zeroBt.onClick.AddListener(() =>
        {
            events.zeroParaEvent.Invoke();
        });

        oneBt.onClick.AddListener(() =>
        {
            int x = 10;
            events.oneParaEvent.Invoke(x);
        });

        twoBt.onClick.AddListener(() =>
        {
            int x = 10;
            string s = "你好呀";
            events.twoParaEvent.Invoke(x, s);
        });

        threeBt.onClick.AddListener(() =>
        {
            int x = 10;
            string s = "你好呀";
            float f = 12.3f;
            events.threeParaEvent.Invoke(x, s, f);
        });
    }
}

最后是测试类,也是监听事件的地方
Test.cs

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

public class Test : MonoBehaviour
{
    public Menu menu;

    private void OnEnable()
    {
        menu.events.zeroParaEvent.AddListener(ZeroPare);
        menu.events.oneParaEvent.AddListener(OnePara);
        menu.events.twoParaEvent.AddListener(TwoPara);
        menu.events.threeParaEvent.AddListener(ThreePara);
    }

    private void OnDisable()
    {
        menu.events.zeroParaEvent.RemoveListener(ZeroPare);
        menu.events.oneParaEvent.RemoveListener(OnePara);
        menu.events.twoParaEvent.RemoveListener(TwoPara);
        menu.events.threeParaEvent.RemoveListener(ThreePara);
    }

    private void ZeroPare()
    {
        Debug.Log("没有参数");
    }

    private void OnePara(int x)
    {
        Debug.Log("一个参数,参数是:" + x);
    }

    private void TwoPara(int x, string s)
    {
        Debug.Log("两个参数,参数是:" + x + "、" + s);
    }

    private void ThreePara(int x, string s, float f)
    {
        Debug.Log("三个参数,参数是:" + x + "、" + s + "、" + f);
    }
}

二、代码挂载及效果

创建四个按钮
在这里插入图片描述
在这里插入图片描述

挂载脚本,实例化按钮
在这里插入图片描述
创建一个空物体,将Test.cs挂载
在这里插入图片描述
将Menu实例化
在这里插入图片描述
运行效果
在这里插入图片描述

  • 4
    点赞
  • 14
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值