Pause menu not called when ESC pressed
Hello everyone!
For my first project I am trying to create a simple PAUSE menu. Once per frame there is a check if ESC is pressed. If yes, than it sets boolean value to true, toggles off Canvas 1 (UI) and toggles on Canvas 2 (pause menu) with multiple buttons. If then ESC is pressed again it reverses the changes (1 on, 2 off, false).
The buttons already work, but the pressing of ESC does nothing. If I manually toggle on Canvas 2 it does toggle off when pressing ESC though.
Thank you in advance for any advice!
Code below: using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.SceneManagement;
public class MainMenu : MonoBehaviour { bool pausedGame = false; public GameObject CanvasA; public GameObject CanvasB;
// Start is called before the first frame update
void Start()
{
CanvasA.gameObject.SetActive(false); //Toggle off when starting
}
// Update is called once per frame
void Update()
{
if (Input.GetKeyDown("escape"))
{
if (!pausedGame)
{
pausedGame = true;
CanvasA.gameObject.SetActive(true);
CanvasB.gameObject.SetActive(false);
}
else
{
pausedGame = false;
CanvasA.gameObject.SetActive(false);
CanvasB.gameObject.SetActive(true);
}
}
}
void OnContinueButton()
{
CanvasA.gameObject.SetActive(false);
CanvasB.gameObject.SetActive(true);
}
void OnRestartButton()
{
SceneManager.LoadScene(SceneManager.GetActiveScene().buildIndex);
}
void OnMainMenuButton()
{
SceneManager.LoadScene(0);
}
void OnQuitButton()
{
Application.Quit();
}
}
Quick update:
I manage to make it work. Solution was also putting script on Canvas B and not only A as well as disabling the start() function. Though I do not really understand why calling it made Canvas A untoggable for the rest of the runtime...
Answer by lvskiprof · Nov 22, 2021 at 05:48 PM
Have you tried using Debug.Log() to show you how the logic is behaving?
I am wondering if you are detecting that the Escape key is down multiple times. Frankly, I am not sure if you only get a single response from the key being pressed or if you might get that response as long as the key is pressed.
Just put some Debug.Log() output inside your if-else blocks and see what it is doing and you should be able to figure it out by watching the Console output.
Answer by Dsiak · Nov 24, 2021 at 01:04 AM
I copy and pasted your code on a testing project and it works fine, the problem might be on another script that is conflicting with your Main Menu