You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Unity按钮点击监听事件未触发的问题求助

Unity按钮点击监听事件未触发的问题求助

我照着Unity 5.3.0的官方文档写了按钮点击监听的代码,结果遇到了麻烦:运行游戏后,Start()里的print(button)确实输出了mybutton (UnityEngine.UI.Button),说明按钮的引用是没问题的,但点击按钮时,绑定的TaskOnClick()方法完全没反应——既看不到"Pressed"的打印,也看不到"You have clicked the button!"的日志。我肯定点的是正确的按钮,因为整个游戏里只有这一个叫这个名字的按钮。

另外我还尝试换成UnityEngine.UIElements.Button来实现,结果直接在button.clicked += TaskOnClick;这行抛出了NullReferenceException(对象引用未设置到对象的实例)。

我的代码如下:

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

public class Hacking : MonoBehaviour
{
    public Button button;

    // Start is called before the first frame update
    void Start()
    {
        print(button);
        button.onClick.AddListener(TaskOnClick);
    }

    void TaskOnClick()
    {
        print("Pressed");
        Debug.Log ("You have clicked the button!");
    }
}

我已经尝试过的方法

  • 改用UnityEngine.UIElements.Button实现点击监听,但触发空引用异常

这个问题和我之前的另一个问题(如何将自定义类数组传递给按钮OnClick调用的方法)有一定关联。

想问问大家,为什么我绑定的监听事件会被忽略呢?


备注:内容来源于stack exchange,提问作者Xaver

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.22 13:28:09