This jump code crashes the editor!

So I started wiring together a jump method for the 2D game that I’ve been working on. Recently I’ve moved away from moving my characters by altering their transform to using rigidbody.movePosition. Everything was working perfectly until I started messing with jump. I’ve isolated this down to just a simple example of the code that’s creating the crash. I’m not entirely sure why this is happening. Any help would be most appreciated!

public float jumpHeight;

void Update () {
    if (Input.GetKeyDown(KeyCode.Space)) {
        jump();
    }
}

void jump () {
    Vector3 jumpedFrom = transform.position;
    
    while (tranform.position.y < jumpedFrom.y + jumpHeight)
        rigidbody.movePosition(transform.position + Vector3.up * Time.deltaTime);
}

The problem is you’re putting it in an endless loop, since rigidbody.MovePosition() doesn’t actually change transform.position, it tells the physics engine to move the object. That is only done the next time the physics engine does its run.

Since the transform.position is not changed by the command:

rigidbody.movePosition(transform.position + Vector3.up * Time.deltaTime);

The while condition (tranform.position.y < jumpedFrom.y + jumpHeight) is never false, hence an endless loop, and the physics engine never gets its turn to run and modify the position.

Also, the while is running in a single frame, so even if it had finished, it would have moved the object all the way to the top in a single frame, which is probably not what you intended.

Here’s an alternative:

public float jumpHeight;
public float targetHeight; // set to the final height of the jump
public bool jumping = false; // set true when moving upwards

void Update () {
    if (Input.GetKeyDown(KeyCode.Space)) {
        targetHeight = transform.position.y + jumpHeight; // set jump height
        jumping = true; // start jump
    }

    // if moving upwards, run the jump
    if (jumping) { 
        Jump();
    }
}

void jump () {
    // if reached target, set jumping to false to stop moving upwards
    if (transform.position.y > targetHeight) {
        jumping = false;
        return;
    }

    // move object upwards
    rigidbody.MovePosition(transform.position + Vector3.up * Time.deltaTime);
}