我如何在游戏视图中隐藏 ui 按钮并在按下退出键时显示该按钮?

How can i hide in game view a ui button and show the button when pressing the escape key?

在我在菜单中所做的编辑器中:GameObject > UI > Button 现在我在层次结构中有一个 Canvas 和一个按钮。 现在我希望当我 运行 游戏时它不会显示按钮,只有当我按下退出键时它才会显示按钮。

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

 public class NodesGenerator : MonoBehaviour {

     public Button btnGenerate;

     private void Start()
     {
         Button btn = btnGenerate.GetComponent<Button>();
         btn.onClick.AddListener(TaskOnClick);
     }

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

我希望当我按下转义键时 btn 会显示并且再次转义时不会显示。 运行 游戏不显示按钮时的默认状态。

假设 "hiding" 意味着您停用了按住按钮的对象,如果您是否按下 Escape 键,则需要签入更新功能。如果你确实点击了它,你只需要反转你的按钮的活动状态,你就完成了。

附带说明一下,在您的 Start 函数中,您不需要再次获取 Button 组件,因为您已经在 btnGenerate 变量中引用了它。所以你可以直接将监听器添加到你的 btnGenerate 变量中。

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

public class NodesGenerator : MonoBehaviour {

    public Button btnGenerate;

     private void Start()
     {
         btnGenerate.onClick.AddListener(TaskOnClick);
     }

     void Update()
     {
         if (Input.GetKeyDown(KeyCode.Escape))
         {
             btnGenerate.gameObject.SetActive(!btnGenerate.gameObject.activeSelf);
         }
     }

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