The question is answered, right answer was accepted
Input key is taken into account several times
Hi,
I created a pause menu, and when i press the key to pause it, it pause and unpause many times (during the time the key is pressed). I change the key in input to try different key, but it happened every time, with every different key. With a print on the script, it print the message several times (during the time the key is pressed too) so i don't understand. The key is pressed something like 0.03-0.05 seconds but it's apparently enough to get about 12-20 print. I tried different input functions (Input.GetButton and Input.GetKey). I know it could work with an Input.GetKeyDown but in this case, the user can't change the key, and i wanted that the user can parameter his own key.
public GameObject PauseUI;
private Player player;
private bool paused = false;
void Start () {
player = GameObject.FindGameObjectWithTag("Player").GetComponent<Player>();
PauseUI.SetActive(false);
}
void Update () {
if (Input.GetButton("Pause"))
{
paused = !paused;
}
if (paused)
{
PauseUI.SetActive(true);
Time.timeScale = 0;
}
if (!paused)
{
PauseUI.SetActive(false);
Time.timeScale = 1;
}
}
public void RESUME()
{
paused = false;
}
public void RESTART()
{
string sceneName = SceneManager.GetActiveScene().name;
SceneManager.LoadScene(sceneName, LoadSceneMode.Single);
}
public void MAINMENU()
{
SceneManager.LoadScene("Main_Menu");
}
public void QUIT()
{
Application.Quit();
}
}
Any help is appreciated, thank you in advance.
Answer by streeetwalker · Mar 01, 2020 at 04:29 PM
Use GetButtonDown instead of GetButton.
GetButton returns true as long as the button is held down - you have to be very fast letting go of the button or key to beat the Update loop timing!
GetButtonDown only fires once per frame. See the unity documentation.
Read your Unity Documentation on the Input Class!
GetButton Returns true while the virtual button identified by buttonName is held down.
GetButtonDown Returns true during the frame the user pressed down the virtual button identified by buttonName.