While loop crashing

Hi

Once more someone (me) has problems with a while loop. I understand logic, but this one is still a riddle to me…

Code:

Angle = 180;
while (!Mathf.Approximately(Angle, 100))
{
     Angle = Mathf.LerpAngle(180, 100, Time.deltaTime);
     DoorVector = new Vector3(transform.localEulerAngles.x, Angle, transform.localEulerAngles.z);
     transform.localEulerAngles = DoorVector;
}

So, while loop will be running while Angle (starts with value 180) isn’t close to 100, and when while loop is running, Angle will drop down to value 100 in 1sec. That means, after 1sec Angle should be appr. 100 and the loop should end, isn’t it?

Why does it crash/freeze?

I don’t see where you are decreasing your value for Angle.The statement Angle = Mathf.LerpAngle(180, 100, Time.deltaTime);always returns a value between 180 and 100. Time.deltaTime returns the time in seconds it took to complete the last frame, so if you have a FPS of 30 Time.deltaTime=1/40, the resulting angle always will be 180-(180-100)/40=178 degree. So you need to add some time dependency to decrease the value.

The problem is that you’re trying to do an entire gradual process within just one frame. You should move your code to the update function or use a coroutine, e.g.:

private IEnumerator LerpDoorAngle(float duration = 1f)
{
    float angle = 180f;
    float startTime = Time.time;
    while (Time.time - startTime <= duration)
    {
        angle = Mathf.LerpAngle(180, 100, (Time.time - startTime) / duration);
        var doorVector = new Vector3(transform.localEulerAngles.x, angle, transform.localEulerAngles.z);
        transform.localEulerAngles = doorVector;
        yield return null;
    }
}

// And then call the coroutine like this:
StartCoroutine(LerpDoorAngle(1f));

The problem with your original loop is that it doesn’t wait until the next frame before checking Time.deltaTime again.