Prodigle Prodigle - 1 month ago 19
C# Question

Unity: Infinite While Loop in Coroutine

Okay so I'm trying to create a small dash coroutine for my 2d character. When the coroutine calls, gravity switches off, he lerps between 2 speeds over a time. The issue is within my Dash coroutine, the while loop checks when time.time(current time) > start time + dash duration.

While debugging this with Mono, I'm finding that my variable currentTime is not changing after being set, even though I can clearly see the while loop running more than once. This puts me in an infinite loop.

Any suggestions?

void Update () {
MoveAndJump ();
CheckDash ();
}




void MoveAndJump(){

if(dashing){
return;
}

Vector2 moveDir = new Vector2 (Input.GetAxisRaw ("Horizontal") * moveSpeed, rb.velocity.y);
rb.velocity = moveDir;

// Consider Switching to an overlap circle based on the actual character graphic. This currently uses a rectangle
// This can also use 4 points to create a more complex box shape. This only works well when using at least about 1 unit size. any smaller and it is innacurate
isGrounded = Physics2D.OverlapArea (groundPoint_right.position, groundPoint_left.position, groundMask);
Debug.Log (isGrounded);

if (Input.GetAxisRaw ("Horizontal") == 1) {
transform.localScale = new Vector3 (1 , 1 * transform.localScale.y, 1* transform.localScale.z);
} else if (Input.GetAxisRaw ("Horizontal") == -1) {
transform.localScale = new Vector3 (-1, 1* transform.localScale.y, 1* transform.localScale.z);
}


if(Input.GetKeyDown(KeyCode.Space) && isGrounded){
rb.AddForce (new Vector2 (0, jumpHeight));
}
}


void CheckDash(){
if(Input.GetKeyDown(KeyCode.W) && !dashing && Time.time > nextdashtime){
dashing = true;
StartCoroutine ("Dash");
}
}

IEnumerator Dash(){
//Before dash loop
rb.gravityScale = 0f;
float startDashTime = Time.time;
float endDashTime = startDashTime + dashDuration;
float currentDashTime;
//Dash Loop
while(Time.time < (startDashTime + dashDuration)){
currentDashTime = Time.time;
// The value to lerp by should be the % that time.time is between start time and end time
rb.velocity = new Vector2 (Mathf.Lerp (startDashSpeed, endDashSpeed, ((currentDashTime - startDashTime) / (endDashTime - startDashTime))),0f);
}

//When dash loop is complete
nextdashtime = Time.time + dashcooldown;
dashing = false;
rb.gravityScale = 1;
yield return null;
}



// FOR CHECKING GROUND CHECK LIMITS
/*void OnDrawGizmos(){
Gizmos.color = Color.red;
Gizmos.DrawLine (groundPoint_left.position, groundPoint_right.position);
}*/


}

Answer

I forgot a yield return null within my while loop that stuck me in an infinite loop. Works fine now.

 while(Time.time < (startDashTime + dashDuration)){
     currentDashTime = Time.time;
    // The value to lerp by should be the % that time.time is between start time and end time
    rb.velocity = new Vector2 (Mathf.Lerp (startDashSpeed, endDashSpeed, ((currentDashTime - startDashTime) / (endDashTime - startDashTime))),0f);
    yield return null;
}