在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

8581

被折叠的 条评论
为什么被折叠?



