- Home /
Minimum value in public variables?
I have public integers that is controlling the size of a generated map. I don't want them to go below a particular value. Is there a way to limit the lower bound similar to [Range(0, 100)]?
edit_1: I could have the script force values lower to be the min, but I'd rather not. I feel like that would be lazier. The only other thing is I could catch it before (once there is more to the project) the script runs.
range take 2 argument $$anonymous$$ and max. I only need a $$anonymous$$
then just use the maxValue of the valueType as maximum
Answer by Orami · Sep 11, 2015 at 08:36 AM
make a public int in the script called lowerBound use the inspector to set it to whatever value you want.
You could also make it private and set it in the script, but public would probably be easier for you to manipulate with the inspector.
Range(lowerBound, 100); //gives a number between lowerBound and 100 or if you want no limit use what ValooFX said and use MaxValue instead of 100;
Answer by booferei · Feb 09, 2017 at 02:05 PM
You can implement OnValidate and force the minimum. For example:
void OnValidate() {
distance = Mathf.Max(distance, 0);
}
This function is called when the script is loaded or a value is changed in the inspector (Called in the editor only).
this is what I really want!
Excellent answer, thanks for $$anonymous$$ching me something new!
See Oferk99's new answer, which seems to supersede $$anonymous$$e.
Answer by Oferk99 · Jun 05, 2020 at 05:54 PM
Code:
[Min(0)]
public int example1;
[Min(0f)]
public float example2;
Code explanation: If you type (in inspector) something under the minimum, after you press enter it will set it back to the minimum. Or in this case - example1 & example2 minimum allowed input in inspector is 0.
WARNING - it only works in inspector, so if you were to set it in code to something under the minimum, it will stay under the minimum.
so in this case:
void function()
{
example1 = -2;
example2 = -2f;
//It will stay -2, even though the minimum is 0
}
Answer by RastaKillah · Oct 24, 2021 at 03:48 PM
BUT, if you want to set a limit to a number later, like "on the fly" , or just to convert:
//If the number is less than the minimum amount, then return that, otherwise return itself
numToMin = numToMin < minOf ? minOf : numToMin;
//As well as clamp does the same, returning the float as maximum
numToMin = Mathf.Clamp(numToMin, preferredMin, numToMin);
You can make a function from that, and probably you can also define a statement to a new temporary number with one line of code.