Move GameObject until he arrives

Hi all,

void Start () {
        rb = GetComponent<Rigidbody2D>();
}
void FixedUpdate () {
        var startPosition = rb.transform.position;
        float step = 100 * Time.deltaTime;
        moveX = Random.Range(-1f, 1f);
        moveY = Random.Range(-1f, 1f);
        targetPosition = new Vector3(moveX, moveY, 0);

        while (startPosition != targetPosition)
        {
            rb.transform.position = Vector3.MoveTowards(startPosition, targetPosition, step);
          
        }
     
    }

I am trying to make the Rigidbody rb move randomly. But somehow when I run this Code, the Unity gets stopped and does not react not all. So Debugging is out of the Option.
The only possible reason that this Code destroys everything is that while loop. Am I tracked in the while loop ?

You need to wait a frame between movements. Probably the simplest would be to use an “if” instead of a while loop.

if(startPosition != targetPosition)
{
  //move
}
1 Like

Your while loop’s condition never becomes false, and so it never exits the while loop, causing unity to enter into an infinite loop and freeze. Also, there’s no reason to use a loop there, as unless you want the object to teleport to the target point, you will want the movement to take place over several frames.

1 Like

Just to add onto this a little bit. You check whether ‘startPosition’ not equals ‘targetPosition’. But this can never happen, because ‘startPosition’ never changes. Your ‘rb.transform.position’ however does. You are looking for:
csharp~~ ~~// if statement because like fire7side said: you want to move over several frames, // and not the entire distance in 1 frame if (rb.transform.position != targetPosition) { // move towards }~~ ~~

EDIT: I might have read a bit too fast. :sweat_smile::smile: