Unity 使用AddListener监听事件与取消监听

Unity中,有时候我们会动态监听组件中的某个事件。当我们使用代码动态加载多次,每次动态加载后我们会发现原来的和新的事件都会监听,如若我们只想取代原来的监听事件,那么就需要取消监听再添加监听了。

如实现如下需求:

如果我们这样编写控制代码:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using TMPro;

public class DynamicDetection : MonoBehaviour
{
    public Button button1;
    public Button button2;
    public TextMeshProUGUI text;
    int index;
    // Start is called before the first frame update
    void Start()
    {
        index = 0;
        button1.onClick.AddListener(delegate
        {
            index++;
            button2.GetComponentInChildren<TextMeshProUGUI>().text = index.ToString();
            button2.onClick.AddListener(SetVal);
        });
    }

    // Update is called once per frame
    void Update()
    {
        
    }

    public void SetVal()
    {
        Debug.Log("来了");
        text.text = "交互了" +  button2.GetComponentInChildren<TextMeshProUGUI>().text +"次";
    }
   
}

运行后我们会发现如下情况:

这明显跟我们需求(每次动态加载都只监听最新的事件)是不一致的。

正确的做法是先取消原来监听再重新监听。

如下:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using TMPro;

public class DynamicDetection : MonoBehaviour
{
    public Button button1;
    public Button button2;
    public TextMeshProUGUI text;
    int index;
    // Start is called before the first frame update
    void Start()
    {
        index = 0;
        button1.onClick.AddListener(delegate
        {
            index++;
            button2.GetComponentInChildren<TextMeshProUGUI>().text = index.ToString();
            button2.onClick.RemoveListener(SetVal);
            //button2.onClick.RemoveAllListeners();
            button2.onClick.AddListener(SetVal);
        });
    }

    // Update is called once per frame
    void Update()
    {
        
    }

    public void SetVal()
    {
        Debug.Log("来了");
        text.text = "交互了" +  button2.GetComponentInChildren<TextMeshProUGUI>().text +"次";
    }
   
}

此处我们可以使用两个方法取消监听,其中一个是RemoveListener方法。不过使用该方法需要注意的是:取消监听的方法需要与之前添加的监听方法相同,否则取消操作将不起作用。

另外我们还可以使用RemoveAllListeners方法。这个方法可以移除指定事件上的所有监听器,而不需要逐个指定要移除的监听器。

相关推荐
qq_428639611 小时前
虚幻基础11:坐标计算&旋转计算
游戏引擎·虚幻
qq_428639611 小时前
虚幻基础09:帧运算
游戏引擎·虚幻
学游戏开发的2 小时前
UE求职Demo开发日志#19 给物品找图标,实现装备增加属性,背包栏UI显示装备
c++·笔记·游戏引擎·unreal engine
土了个豆子的7 小时前
unity中的动画混合树
unity·游戏引擎
学游戏开发的8 小时前
UE学习日志#19 C++笔记#5 基础复习5 引用1
c++·笔记·学习·游戏引擎·unreal engine
奔跑的犀牛先生10 小时前
unity学习26:用Input接口去监测: 鼠标,键盘,虚拟轴,虚拟按键
unity
Dr.勿忘20 小时前
C#面试常考随笔8:using关键字有哪些用法?
开发语言·unity·面试·c#·游戏引擎
存储服务专家StorageExpert21 小时前
答疑解惑:如何监控EMC unity存储系统磁盘重构rebuild进度
运维·unity·存储维护·emc存储
Petrichorzncu1 天前
Games104——游戏引擎Gameplay玩法系统:基础AI
游戏引擎
追逐梦想永不停1 天前
Unity实现按键设置功能代码
unity