- Home /
Mathf.Clamp an int value
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?
Answer by Mrroundtree22 · Mar 05, 2021 at 03:44 PM
I just put
if (myNum > 1000)
{
myNum = 1000;
}
At the end of my method and that worked fine.
Well, if this works, using Clamp or Min does work exactly the same. Mathf.Min is literally defined like this.
If your manual if statement works, the Clamp or Min call would work exactly the same. You haven't posted your original code in your question, so we don't know how you actually used it in your case so we can not tell what you did wrong. However your answer implies that Clamp or Min does not work which is not the case.
I'm not disagreeing with you. I genuinely don't know why clamp isn't working for me.
Answer by Bunny83 · Mar 05, 2021 at 01:54 PM
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 ^^.
The documentation is clear but that doesn't solve my problem unfortunately. I've done exactly as you and the documentation described but the number still goes over 1000. I don't understand why.
Answer by TKDHayk · Mar 06 at 02:34 AM
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.
Your answer
Follow this Question
Related Questions
Number Range 3 Answers
Does anyone know why this is wrong? 2 Answers
Making a plain number range 2 Answers
detect if a variable has stop increasing 4 Answers