Exportforce
Exportforce

Reputation: 97

Autofilling slider sometimes not at 100%

I am filling a slider from zero to max with this function:

IEnumerator FillBar() {
    float runtime = manualTime;
    for(float f = 0; f <= runtime; f += Time.deltaTime) {
        manualSlider.value = Mathf.Lerp(0, 1000, f/runtime);
        yield return null;
    }}

But no matter if I use "Whole Numbers" or not it either often stops at 998 (+/- a few) and without whole numbers it stops at 998.XXXX I have a solution to "cheat" around that problem and reset it manually after it "filled up" with this code

    IEnumerator FillBar() {
    float runtime = manualTime;
    for(float f = 0; f <= runtime; f += Time.deltaTime) {
        manualSlider.value = Mathf.Lerp(0, 1000, f/runtime);
        yield return null;
    }
    manualSlider.value = 0;
    //stuff happening here
}

The problem I am facing is that I want to use the full slider value as trigger for what happens when the slider is filled but when it never reaches 1000 (I even tried with just 1, too. Same problem) Is there a good fix for this ?

Upvotes: 0

Views: 175

Answers (1)

Fiffe
Fiffe

Reputation: 1256

It rarely is gonna reach full value when you're using interpolation with Time.deltaTime. You need to snap your slider to max value when the interpolation ends.

Try this coroutine instead:

IEnumerator FillBar(float _time) {
    float _elapsedTime = 0;

    while(_elapsedTime < _time)
    {
        manualSlider.value = Mathf.Lerp(manualSlider.value, 1, (_elapsedTime/_time));
        _elapsedTime += Time.deltaTime;

        yield return null;
    }

    manualSlider.value = 1;
}

Upvotes: 1

Related Questions