Search Unity

Bug Why doesn't the bool value change?

Discussion in 'Scripting' started by Lex_212, Apr 24, 2022.

  1. Lex_212

    Lex_212

    Joined:
    Oct 3, 2020
    Posts:
    84
    Hi ,I have this code:
    Code (CSharp):
    1.  
    2. if (Input.GetButtonDown("Cancel") && gameIsPaused == false)
    3. {
    4.     gameIsPaused = true;
    5. }
    6. if (Input.GetButtonDown("Cancel") && gameIsPaused == true)
    7. {        
    8.     gameIsPaused = false;
    9. }
    10.  
    The problem is that the gameIsPaused bool does not change to true when I press the button, but if I change the bool in the inspector to true and then press the button, the bool value becomes false.
    Why does that happends?
    Thanks
     
  2. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    38,745
    Because the first check happens, you set the bool true... then in the SAME EXACT FRAME, the second if flows and actually succeeds.

    The above code is a classic example of "repeating yourself."

    The DRY principle states "don't repeat yourself."

    Let me offer you a better way:

    Code (csharp):
    1. if (Input.GetButtonDown("Cancel"))
    2. {
    3.   // toggle on / off
    4.   gameIsPaused = !gameIsPaused;
    5. }
    Note how there is no repeated code.
     
    Bunny83 and JonArnt like this.
  3. passerbycmc

    passerbycmc

    Joined:
    Feb 12, 2015
    Posts:
    1,741
    the way kurt offers is much better and easier to read, but also if you do hit similar cases and its not just a toggle, making your 2nd statement a "else if" would have ensured on any given frame only one of those 2 blocks executes
     
    Bunny83 likes this.