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

Unity开发中点击主菜单继续按钮后如何禁用所有UI按钮的点击交互?

实现方案

你可以通过UGUI原生的交互控制属性实现「按钮保持显示但禁止点击」的需求,以下是三种常用实现方式,按需选择即可:

方案1:CanvasGroup统一控制(最推荐,维护成本最低)

如果你的主菜单按钮都在同一个父物体下,用该方案最方便:

  • 在Unity编辑器中把所有需要控制的主菜单按钮(新游戏、继续、选项、退出)放到同一个父物体下(可命名为MainMenuButtons)
  • 给该父物体添加CanvasGroup组件
  • 在你的UIController脚本中添加变量:
using UnityEngine.UI; // 注意顶部引入UI命名空间

public CanvasGroup mainMenuCanvasGroup;
  • 回到Unity编辑器,把刚才的父物体拖拽到mainMenuCanvasGroup变量的赋值槽中
  • 在ContinueGameButton方法的第一行添加禁用逻辑:
public void ContinueGameButton()
{
    // 先禁用所有按钮交互,防止重复点击
    mainMenuCanvasGroup.interactable = false;

    transform.GetComponent<AudioSource>().Play();
    LoadSceneForSavedGame = true;
    newGameDialog.SetActive(false);
    StartCoroutine(sceneFader.FadeAndLoadScene(SceneFader.FadeDirection.In, _newGameButtonLevel));
}

该方案会直接禁用父物体下所有可交互UI的点击功能,不需要单独配置每个按钮,后续新增菜单按钮也不需要修改代码。

方案2:单独控制指定按钮

如果你的按钮位置分散,无法放到同一个父物体下,可以单独为每个按钮配置:

  • 在UIController脚本中添加按钮变量:
using UnityEngine.UI;

public Button newGameBtn;
public Button continueBtn;
public Button optionsBtn;
public Button quitBtn;
  • 回到编辑器,把四个对应的按钮分别拖拽到对应变量的赋值槽中
  • 添加禁用按钮的公共方法:
private void DisableAllMenuButtons()
{
    newGameBtn.interactable = false;
    continueBtn.interactable = false;
    optionsBtn.interactable = false;
    quitBtn.interactable = false;
}
  • 在ContinueGameButton方法开头调用该方法:
public void ContinueGameButton()
{
    DisableAllMenuButtons();

    // 原有逻辑保持不变
    transform.GetComponent<AudioSource>().Play();
    LoadSceneForSavedGame = true;
    newGameDialog.SetActive(false);
    StartCoroutine(sceneFader.FadeAndLoadScene(SceneFader.FadeDirection.In, _newGameButtonLevel));
}

方案3:自动遍历子物体按钮(无需手动赋值)

如果按钮都在同一个父物体下,又不想手动配置每个按钮,可以用自动遍历的方式:

  • 在UIController脚本中添加父物体变量:
using UnityEngine.UI;

public Transform menuButtonParent;
  • 编辑器中把按钮的父物体拖拽到变量槽中
  • 修改禁用方法为自动遍历:
private void DisableAllMenuButtons()
{
    // 遍历父物体下所有按钮组件,批量禁用交互
    foreach (Button btn in menuButtonParent.GetComponentsInChildren<Button>())
    {
        btn.interactable = false;
    }
}
  • 同样在ContinueGameButton开头调用该方法即可。

注意:如果你的按钮有自定义的禁用态样式,设置interactable = false后会自动切换到禁用样式;如果不需要样式变化,只需要屏蔽点击,可以把CanvasGroup的blocksRaycasts属性设为false,效果相同且不会修改按钮的视觉状态。

内容的提问来源于stack exchange,提问作者Daniel Lip

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.11 18:00:01