My code is infinitely looping, Can anyone tell me Why?

I’m writing a jump functionality with control of animation as well. ,The code i wrote is infinitely looping (while loop inside Coroutine) and unity gets stuck mid of an animation. I am unable to see a problem with my logic. Can anyone point out where I am going wrong? has it something to do with how unity works that I don’t yet understand?

void Update()
{
Movement();
}

private void Movement()
{
    float move = Input.GetAxisRaw("Horizontal");
    _rigidbody.velocity = new Vector2(move * _speed, _rigidbody.velocity.y);
    _playerAnim.MoveAnimation(Mathf.Abs(move));

    //flip sprite
    if (move > 0)
    {
        _spriteRenderer.flipX = false;
    }
    else if (move < 0)
    {
        _spriteRenderer.flipX = true;
    }
    //end of flip sprite

    if (Input.GetKeyDown(KeyCode.Space) && _canJump)
    {
        
        _playerAnim.JumpAnimation(true);
        _rigidbody.velocity = new Vector2(_rigidbody.velocity.x, _jumpHeight);
        StartCoroutine(ResetJumpCoroutine());

    }
}

IEnumerator ResetJumpCoroutine()
{
    _canJump = false;
    yield return new WaitForSeconds(.35f);
    while (!_canJump)
    {
        RaycastHit2D hitInfo = Physics2D.Raycast(transform.position, Vector2.down, 1f, 1 << 6);
        Debug.DrawRay(transform.position, Vector2.down * 1f, Color.green);
        if (hitInfo.collider != null)
        {
            Debug.Log("Hit ::: " + hitInfo.collider.name);
            _playerAnim.JumpAnimation(false);
            _canJump = true;
        }
    }
}

If you have an infinite loop then you need to look at your loops and the clauses for them.


probably here:

_canJump = false;
yield return new WaitForSeconds(.35f);
while (!_canJump)

You are setting the loop condition to always false then you are in the while saying if it is false continue to loop almost immediately afterwards.


         if (hitInfo.collider != null)
         {
             Debug.Log("Hit ::: " + hitInfo.collider.name);
             _playerAnim.JumpAnimation(false);
             _canJump = true;
         }

Then you are saying if you have detected a collision set it to true.


Ergo: You arent ever hitting that line. Maybe add a break point an see what state the application is in at the start of that if statement or check that the thing you are expecting a collision on has a collider.