I'm using Unity 2d right now and I'm making some inventory Ui but I cant seem to figure out how to open and close UI with one key. like in most games when you press escape and it opens a pause screen then if you press it again then it closes it. I'm not sure how I can get what I'm looking for. but I tried it and here is what I have
if(Input.GetKeyDown(KeyCode.Tab)) {
GameMenu.SetActive(true);
if(GameMenu.activeSelf && Input.GetKeyDown(KeyCode.Tab)) {
GameMenu.SetActive(false);
}
}
CodePudding user response:
The easiest way is to use a bool variable to store the state of UI, like:
private bool isMenuActive = false;
if (Input.GetKeyDown(KeyCode.Tab))
{
if (isMenuActive)
{
GameMenu.SetActive(false);
isMenuActive = false;
}
else
{
GameMenu.SetActive(true);
isMenuActive = true;
}
}
Or more consice:
private bool isMenuActive = false;
if(Input.GetKeyDown(KeyCode.Tab))
{
isMenuActive = !isMenuActive;
GameMenu.SetActive(isMenuActive);
}
Or more consice:
if(Input.GetKeyDown(KeyCode.Tab))
{
GameMenu.SetActive(!GameMenu.activeSelf);
}