I want to clamp an int so that its value never goes above 1000 (I want it so that it never goes above this number if I have 999 + 20 the result should still be 1000). I’ve read documentation but I still can’t seem to get it to work. Could somebody explain it to me?
I think the documentation is already as clear as possible. The Clamp method returns the clamped value and ensures that it’s between min and max.
yourValue = Mathf.Clamp(yourValue, 0, 1000);
Though If you just want to “clamp” the max value but you don’t need a min value, you could simply use “Mathf.Min” instead:
yourValue = Mathf.Min(yourValue, 1000);
Just for completeness, if you only need a min value but no max value you can use “Mathf.Max” instead:
yourValue = Mathf.Max(yourValue, 0);
Mathf.Clamp can be emulated with a Min and Max call chained together. Those two lines to exactly the same thing:
yourValue = Mathf.Min(Mathf.Max(yourValue, minVal), maxVal);
yourValue = Mathf.Clamp(yourValue, minVal, maxVal);
The Min and Max functions are simply defined as
public static int Min(int a, int b)
{
if (a > b)
return b;
return a;
}
public static int Max(int a, int b)
{
if (a > b)
return a;
return b;
}
This is all rather trivial math / logic. Hopefully this clears up the last confustion about the usage ^^.
I just put
if (myNum > 1000)
{
myNum = 1000;
}
At the end of my method and that worked fine.
Clamping the value does not prevent it from ever rising above the max.
Clamping a value simply returns the value, constrained within the min and max.
You can use Mathf. Clamp when retrieving the value to constrain it, but it is not a permanent constraint. It simply returns the number within the min/max range.
myNum = Mathf.Min(newValue, 1000);