I’ve been looking at videos, the manual, and a handful of other places, but I can’t find anything that helps.
Basically I got a variable, which increases in value when a condition is met, and decreases when it isn’t. And I want it to not be able to go below 0, and above 10 (it’s a float btw).
I did find out about the Range attribute:
[Range(0,10)]
But that just changes the Inspector view of the variable into a slider, and doesn’t actually limit how far the value can go at runtime.
I also tried doing stuff with “Mathf.Clamp” but that didn’t work either" (I most likely used it incorrectly in my case).
You can use a Property.
public float MyNumber
{
get { return _myNumber; }
set { _myNumber = Mathf.Clamp(value, 0, 10); }
}
private float _myNumber;
This is a property with a backing field. You access it via MyNumber and any set call will run through set{}, which in the above case uses a Clamp to constrain it between 0 and 10.
3 Likes
I’d like to add on that you can preserve the usual inspector functionality like this:
public float MyNumber {
get { return _myNumber; }
set { _myNumber = Mathf.Clamp(value, 0, 10); }
}
[SerializeField, Range(0, 10)] private float _myNumber;
Just be aware that the inspector cannot trigger property code unless more logic is written via OnValidate or something.
So in this case the value is clamped in the inspector by the “Range()” attribute, but at runtime it’s clamped by the property. Both will need to be updated if the upper/lower bounds change unless you want to define constants for those values.
2 Likes
Where should I put this?
If I put it in either the Start or Update method, I’m getting the "Unexpected Symbol ‘public’ "
And if I put it outside of them, it doesn’t clamp it.
It goes outside the methods inside the class, as if you were defining a new variable.
Make sure you’re only using the public property, not the private backing variable.
ie.
MyNumber = 11; // will clamp to 10
_myNumber = 11; // wont clamp
1 Like
It’s defined like a regular variable, so do it in the class scope.
public class MyClass
{
public float MyNumber
{
get { return _myNumber; }
set { _myNumber = Mathf.Clamp(value, 0, 10); }
}
[SerializeField, Range(0, 10)] private float _myNumber;
public void Start()
{
// nada
}
public void Update()
{
MyNumber += Time.deltaTime / 12;
}
}
2 Likes