Jim
Jim

Reputation: 801

Why doesn't this example of Mathf.Clamp work?

I'm trying to simply get from 0 to 1 in 2 seconds, without exceeding 0 or 1.

    Mathf.Clamp(buttonPercent += (0.5f * Time.deltaTime), 0, 1.0f);

This causes my number to increase past 1.

I know a simple way would be to do something like this

buttonPercent += 0.5f;
if(buttonPercent > 1){
    buttonPercent = 1;
}

...but I'm curious why my clamp method isn't working.

Thanks!

Upvotes: 1

Views: 145

Answers (1)

Bizhan
Bizhan

Reputation: 17085

Mathf.Clamp returns the clamped value and does not change the input as it's a call by value.

Change it to:

buttonPercent = Mathf.Clamp(buttonPercent + (0.5f * Time.deltaTime), 0, 1.0f);

Upvotes: 2

Related Questions