I want the sound that plays when I press esc to pause the game, not play again when I press esc again while the pause menu is open

I’m trying to learn FMOD with unity integration, but I’m not a good person on scripting, but I need to learn, so I’m training in a project from the asset store, the creator kit FPS, when the ESC key is pressed the game go to pause, but if you press the key again the pause menu doesn’t close and the sound using the fmod script code play again. How do I say to C# and unity that I want the sound to play just when the pause menu open?

but if you press the key again the pause menu doesn’t close and the sound using the fmod script code play again.

This is how the tutorial project was originally programmed… you can test this by adding a simple Debug.Log() line in the if-statement. It will get called every time you press the ESC key, but the menu will not close (check in the console):

    if (CanPause && Input.GetButtonDown("Menu"))
    {
        PauseMenu.Instance.Display();
        Debug.Log("opening menu");
    }

How to solve this problem? First, we need to find a way to close the menu. To display the menu the game calls PauseMenu.Instance.Display(); So the best place to look for might be the PauseMenu.cs script. Open that up and you will find a ReturnToGame method, you can use that. Since the game is checking if the boolean variable CanPause is true before displaying the menu, we can set it to false in the if-statement and add an else if clause checking if it is false and close the menu with the ReturnToGame method if it is the case:

    if (CanPause && Input.GetButtonDown("Menu"))
    {
        PauseMenu.Instance.Display();
        CanPause = false;
    }
    else if (!CanPause && Input.GetButtonDown("Menu"))
    {
        PauseMenu.Instance.ReturnToGame();
        CanPause = true;
    } 

Setting CanPause to true will allow the game to open the menu again and vice versa.
Now you can add your sound to the if-statement and it should just play one time when opening the menu. Happy learning!

2 Likes