Search Unity

Question Need help implementing pause screen - Button selected by default makes functions run twice

Discussion in 'UGUI & TextMesh Pro' started by gregsantos, Nov 27, 2020.

  1. gregsantos

    gregsantos

    Joined:
    May 12, 2018
    Posts:
    2
    On it's core, the problem I need to solve is "how do I stop a button from being pre-selected when it appears again on the screen" - I will try to explain better and give more context below.

    I'm trying to implement a simple pause menu in my game. To pause, the player presses the spacebar. To unpause, they can either press the spacebar, or click a "resume game" button.

    The issue is when the player pauses (spacebar), resumes by clicking the button, pauses again (spacebar), and tries to resume with the spacebar - it doesn't resume the game.

    After some investigating, I found out that the "Toggle Pause" function gets called twice. Once because the spacebar was pressed, and once because it thinks the "resume" button was pressed (pressing space makes it activate the button).

    I believe this is because it thinks I'm hovering or have the button "selected". If I click anywhere else in the screen, it works normally again.

    One way to fix it would be to just change the pause key (like use Esc instead of Space), but that doesn't fix the core issue, that is the button being "selected" when it shouldn't be.

    Is there a way to tell Unity "ok, when I click this button, do these things, and de-select the button after that"?

    Please let me know if it isn't clear enough :)

    My code:
    Code (CSharp):
    1.     private void Update()
    2.     {
    3.         // Check if player pressed the spacebar to pause or unpause
    4.         if (Input.GetKeyDown(KeyCode.Space))
    5.         {
    6.             TogglePause();
    7.         }
    8.     }
    9.  
    10.     // Change the pause status (paused or not)
    11.     void TogglePause()
    12.     {
    13.         // If it's not paused, then pause it (time stops, and brings up pause menu)
    14.         if (!isPaused)
    15.         {
    16.             Time.timeScale = 0f;
    17.             isPaused = true;
    18.             pauseCanvas.SetActive(true);
    19.         }
    20.         else // If it was paused, then unpause (time starts running, and closes pause menu)
    21.         {
    22.             Time.timeScale = 1f;
    23.             isPaused = false;
    24.             pauseCanvas.SetActive(false);
    25.         }
    26.     }
    27.  
    28.     public void Pause_ResumeButton() // This is activated by the button
    29.     {
    30.         TogglePause();
    31.     }
    32.