Reply To: How to change transform.rotation

Forum Archive How to change transform.rotation Reply To: How to change transform.rotation

#36652
Jonathan Gonzalez
Participant

    @eithman Without the yield it’ll execute the entirety of the while loop almost instantly. Adding yield return null essentially makes it work in a similar way to the update method. It waits a frame before going through the loop again. So it goes through the while loop once, waits a frame, goes through again, waits a frame and does this over and over until the condition used for the while loop is met. In this case that’s the elapsed time being less than 5. 

    The way the coroutine was written before should work correctly. The while loop will only be looped when elapsed time is less than 5. Once it reaches 5 or greater it should get out of the loop and finish off the rest of the coroutine. 

    If you add a Debug.Log at the end where your coroutine should end you should see it appear once elapsedTime is at or greater than 5. Here is an example

    IEnumerator FindFood()
    {
    rotateAmount = new Vector3(0, transformObj.eulerAngles.y + 90, 0);
    startRot = transform.rotation;
    endRot = Quaternion.Euler(rotateAmount);
    
    while (elapsedTime < 5){
    elapsedTime += Time.deltaTime;
    transform.localRotation = Quaternion.Lerp(startRot, endRot, elapsedTime / 5);
    yield return null;
    }
    elapsedTime = 0;
    Debug.Log("Coroutine is completed");    
    }