如何隐藏游戏视图中的UI按钮并在按下退出键时显示按钮?
问题描述:
在编辑器中我在菜单中做了:GameObject> UI> Button 现在我在层次结构中使用一个按钮的画布。 现在我想要当我运行游戏时,它不会显示按钮,只有当我按下退出键时,它会显示按钮。如何隐藏游戏视图中的UI按钮并在按下退出键时显示按钮?
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将显示并再次逃脱不会显示。运行游戏时的默认状态不显示按钮。
答
想象一下,通过“隐藏”,您意味着您停用了持有按钮的对象,如果您按下了Escape键,则需要检查Update功能。如果你确实击中了它,你只需要扭转按钮的活动状态,就完成了。
作为一个方面说明,在您的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!");
}
}