如何在游戏视图中隐藏 UI 按钮并在按下 Esc 键时显示该按钮?



在编辑器中,我在菜单中做了:游戏对象> UI>按钮 现在我在层次结构中有一个带有按钮的画布。 现在我希望当我运行游戏时它不会显示按钮,只有当我按下 esc 键时它才会显示按钮。

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 将显示并且不会再次显示转义。运行游戏时的默认状态是不显示按钮。

想象">

隐藏"意味着您停用了按住按钮的对象,如果您点击了 Esc 键,则需要检查更新功能。如果你确实点击了它,你只需要反转按钮的活动状态,你就完成了。

作为旁注,在 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!");
}
}

最新更新