Search Unity

If statement ignored for some reason

Discussion in 'Scripting' started by matias-e, Feb 23, 2015.

  1. matias-e

    matias-e

    Joined:
    Sep 29, 2014
    Posts:
    106
    Hi, I'm very new to scripting and I ran into a problem where I'm trying to change the force added to a cube by pressing space. However, for some reason when I run the game, the force is being added automatically, even when I'm not pressing space. What could be the cause here?

    Code (CSharp):
    1. void Update ()
    2.     {
    3.    
    4.         float moveHorizontal = Input.GetAxis("Horizontal");
    5.         float moveVertical = Input.GetAxis("Vertical");
    6.  
    7.         Vector3 movement = new Vector3(moveHorizontal, 0.0f, moveVertical);
    8.        
    9.         rigidbody.AddForce(movement * 10);
    10.  
    11.         if(Input.GetKeyDown(KeyCode.Space));
    12.            moverUp();
    13.  
    14.     }
    15.  
    16.  
    17.     void moverUp ()
    18.     {
    19.            
    20.         rigidbody.AddForce(0, 10, 0);
    21.    
    22.     }
    23.  
    Thanks!
     
  2. Strategos

    Strategos

    Joined:
    Aug 24, 2012
    Posts:
    255
    The semi colon after your if statement ?
     
    Schneider21 likes this.
  3. Schneider21

    Schneider21

    Joined:
    Feb 6, 2014
    Posts:
    3,512
    As @Strategos said, the semi-colon breaks it. What you have is essentially the same as
    Code (CSharp):
    1. if(Input.GetKeyDown(KeyCode.Space)) {
    2.   // Do nothing
    3. }
    4. moverUp();
    This is a good reason why you should always add brackets to your control statements and never shorthand them. A few extra lines in your code make it much easier to read and troubleshoot, and it all gets compiled down anyway.
     
  4. matias-e

    matias-e

    Joined:
    Sep 29, 2014
    Posts:
    106
    Works now, thanks for clearing it up! Still don't have a great understanding of syntax, heh.