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方法。这个方法可以移除指定事件上的所有监听器,而不需要逐个指定要移除的监听器。

相关推荐
RReality9 小时前
【Unity Shader URP】色带渐变着色(Ramp Shading)实战教程
ui·unity·游戏引擎·图形渲染
mxwin17 小时前
Unity URP 体积光与雾效 基于深度重建世界空间位置,实现体积雾与体积光
unity·游戏引擎
张老师带你学18 小时前
unity 树资源 有樱花树 buildin
科技·游戏·unity·游戏引擎·模型
魔士于安18 小时前
unity 植物 不常见 花 触手植物
游戏·unity·游戏引擎·贴图·模型
魔士于安19 小时前
unity=>传送门特效 带自由视角旋转放大 鼠标操作
前端·游戏·unity·游戏引擎·贴图·模型
南無忘码至尊20 小时前
Unity学习90天 - 第4天 - 认识物理系统基础并实现物体碰撞反弹
学习·unity·游戏引擎
南無忘码至尊20 小时前
Unity学习90天 - 第4天 - 学习预制体 Prefab + 实例化并实现按鼠标生成子弹
学习·unity·游戏引擎
魔士于安1 天前
Unity资源Toon City Pack 发电厂 工地 公园 地铁站口 银行 车 直升飞机 可动 URP
游戏·unity·游戏引擎·贴图·模型
SmartRadio1 天前
NRF52833 + MPU6050 室内定位跟随无人机
游戏引擎·无人机·cocos2d
心前阳光2 天前
Unity之运行时标准材质半透明无效果
unity·游戏引擎·材质