I have indeed noticed this problem, “” does not work most (if not all) of the time, so you need a second if statement. “Else” also won’t help, it requires an alternate set of requirements to be filled (it basically says “or”, not “and”) so if{ if{ }} is how to do it.
In OP’s case, the quickest fix is to put an else. He already has the “alternate set of requirements”.
“else” does not basically say “or”; It says “otherwise”, or “Now for something completely different”.
Allow me to walk you through the OP’s code
//Pause/Unpause Game
//if the Q key was depressed this frame the gamePaused variable is false
if(Input.GetButtonDown("Q") gamePaused == false){
//do our stuff: pause the game, and set the flag to true
Time.timeScale = 0;
gamePaused = true;
}
//if the Q key was depressed this frame the gamePaused variable is true
//without the else, it will always flow into this if
//if gamePaused were false, then the first if will change it true
//if it were true, then it will not have gone in the first if, but still come through here
if(Input.GetButtonDown("Q") gamePaused == true){
Time.timeScale = 1;
gamePaused = false;
}
Now for an efficiency fix, which may look like Orbitus’s suggest answer of an if inside an if, but it’s not for the reasons of treating elses like ors and ands being faulty.
Edit: Bah, Democre replied as I was typing out mine, basically saying the exact same thing.
Then you have observed incorrectly.
There is nothing wrong with ‘’ it works perfectly fine. If you have code with a conditional statement using which doesn’t work as expected then either you expectations/logic (as in the case of the OP) or code is wrong.
As for the OP the problem is simple, if the first conditional check evaluates to true, then the second conditional must also evaluate to true due to the change of ‘gamepaused’ by the first, resulting in both if statements being executed, thus pausing then un-pausing the game in a single update. Hence why an else check is required.
For example
Assume that ‘Input.GetButtonDown(“Q”)’ is true and gamePaused is false.
The first if statement will evaluate to true and will change gamePaused to true.
Since ‘Input.GetButtonDown(“Q”)’ will not change its value half-way through Update it is still true for the second if statement and as the previous conditional check set gamePaused to true, the second if statement now also evaluates to being true.
Its would be easy to check, just add a Debug.Log() statement to each conditional check and you’ll see that is what is happening.
Normally in these situations I would find it easier to split the check into a hierarchy chain e.g.