- Home /
How can i show the ui button only when pressing on the escape key ?
In the editor i did in the menu: GameObject > UI > Button Now i have in the Hierarchy a Canvas and a Button. What i want to do is when running the game not to show the button and only when pressing on the escape key show the button.
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!");
}
Just a quick note, btnGenerate is already a Button, creating a new reference btn of type Button to get the Button component results in the same thing. You could just do :
btnGenerate.onClick.AddListener (TaskOnClick);
Answer by LucyLuna · Apr 11, 2017 at 06:55 AM
I hope this helps. wink :)
void Start(){
btnGenerate.gameObject.SetActive(false);
}
void Update(){
if(Input.GetKey(KeyCode.Escape)){
btnGenerate.gameObject.SetActive(true);
}
}
Answer by projojoboy · Apr 06, 2018 at 03:11 PM
Hey, I assume you want to make a menu type thing, this is one of the simplest ways to do this.
[SerializeField] GameObject button;
private bool isActive = false;
private void Update()
{
if (Input.GetKeyDown(KeyCode.Escape) && isActive)
button.SetActive(true);
else if (Input.GetKeyDown(KeyCode.Escape) && !isActive)
button.SetActive(false);
}
The only thing you have to do after this is dragging the button into the game object slot in the inspector.
This toggles the button on and off when you press the escape key.
Your answer
Follow this Question
Related Questions
Why when creating new animator controller for the character the character is not walking right ? 0 Answers
How can i Instantiate on the terrain from left to right ? 0 Answers
Why the tile map scripts take almost all the cpu usage ? cpu usage is getting to 99% at times 1 Answer
How can i rotate object by pressing on key R and keep object facing to me my self ? 0 Answers
How can i spawn new gameobjects to be inside the terrain area ? 2 Answers