Jim Jim - 18 days ago 9
C# Question

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!

Answer

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);