Mathf.Lerp inside a while loop crashes game

I want to make a method so that when you overload the “ChangeNumberTo” method it lerps the value over a certain amount of time to the target value.

private float number;

void Start()
{
    number = 0;
    ChangeSpeedTo(15, 5);
}

void ChangeNumberTo(float targetValue, float transitionTime)
{
    while (number < targetValue)
    {
        number = Mathf.Lerp(number, targetValue, Time.deltaTime * transitionTime);
    }
}

The only problem is that whenever I call this method, the game crashes. How do I make it work?

I think you’ve confused Mathf.Lerp with Mathf.MoveTowards. The latter should work more like you intended it to - with every call it brings the value of number closer to the targetValue. Mathf.Lerp returns an interpolated value, calculated from the first two parameters (the “start” and “end” values) and the thirds parameter t, which is a value between 0.0f and 1.0f.

You have several issues in your code.

First of all the way you use lerp you never really reach the target value. The change each step will get smaller and smaller so it gets slower and slower.

You may want to either use MoveTowards instead of Lerp or use a wider range for the exit condition.

The next issue is that your whole code just makes no sense, even if you get the transition working correctly. Your while loop will execute within the first frame before anything is drawn. You would need to either make it a coroutine where you have a yield return null; inside your loop, or you have to put this code inside Update without the while loop.

Commonly you would create a coroutine like this:

void Start()
{
    number = 0;
    StartCoroutine(ChangeSpeedTo(15, 5));
}
IEnumerator ChangeNumberTo(float targetValue, float transitionTime)
{
    while (Mathf.Abs(number - targetValue) < 0.01f)
    {
        number = Mathf.Lerp(number, targetValue, Time.deltaTime * transitionTime);
        yield return null;
    }
    number = targetValue;
}