Search Unity

IF statement not running in Update

Discussion in 'Scripting' started by Kitos14, Sep 19, 2017.

  1. Kitos14

    Kitos14

    Joined:
    Nov 1, 2014
    Posts:
    2
    I am running an if statement inside FixedUpdate which will stop an object to move. But when it comes at the if which would make variable "isMoving = false" it doesn't do it. Instead it repeats FixedUpdate and will run the other if... so the object is moving constantly after reaching the last position between to small positions up and down. Can anyone help me?
    Code :
    Code (CSharp):
    1.     void FixedUpdate() {
    2.         if (isMoving == false) {
    3.             calculateNextMovePosition ();
    4.             isMoving = true;
    5.         } else {
    6.             if (rb.position.y < nextPosition) {
    7.                 rb.velocity = move.normalized * 8;
    8. // This if...                if (rb.position.y >= nextPosition) {
    9.                     isMoving = false;
    10.                 }
    11.             } else if (rb.position.y > nextPosition) {
    12.                 rb.velocity = -move.normalized * 8;
    13. // And this if                if (rb.position.y <= nextPosition) {
    14.                     isMoving = false;
    15.                 }
    16.             }
    17.         }
    18.     }
     
  2. Brathnann

    Brathnann

    Joined:
    Aug 12, 2014
    Posts:
    7,187
    Within your else, you are check if rb.position.y < nextPosition, then you're doing something before trying to do another if check to see if it's >= nextPosition. My guess is the if never happens because it's never less then and then greater then within that single loop. So the next time fixedUpdate runs it becomes greater, so your else if runs, but once more it is never greater and then less then in the same loop.

    Thus, your character keeps moving. I don't have a solution for you because I don't know what exactly you're trying to do. What does calculateNextMovePosition do? and can you give a better description of what you want to achieve.