Range variable not working? or am I doing something wrong

I am trying to use a range attribute variable to restrict the rotation of a camera.

I created a range like this

[SerializeField][Range(-30,30)] float YAxisValue=0;

I then set the rotation of the camera like so

transform.rotation = Quarternion.Euler(new Vector3(0,YAxisValue,0);

The idea is that as I am only changing a float and then using absolute angles I should not fall into any Quarternion issues when checking the angle as that is just a float. I thought that a range would restrict the values and it does when adjusting through the Inspector. If i adjust in code though it just sails past the restrictions. In this case I just did a YAxisValue+=0.1f; expecting it to stop at 30. Instead it just goes round and around.

Am I expecting too much of a Range? Or am I doing something wrong with it?

I thought that a range would restrict the values and it does when adjusting through the Inspector. If i adjust in code though it just sails past the restrictions.

That is exactly how things are supposed to work. Adding a Range attribute will do nothing to restrict the value through code, what the attribute does is tell the editor how to serialize and interpret the field to display it correctly, however it won’t affect your code at all. If you want to restrict the value what you need to do is use Mathf.Clamp to filter your value through a min and max value. If you are working inside update then you should clamp YAxisValue right before using it to create the rotation. If you are doing your work elsewhere you should probably clamp the value right after any assignment to YAxisValue.

You could also add a property to your class so when handling the value in the code you do it through that property with a set m-ethod that clamps the value before assignment. Something like this:

[SerializeField][Range(-30f,30f)]
private float yAxisValue;

public float YAxisValue
{
    get { return yAxisValue;}
    set
    {
        float clampedValue = Mathf.Clamp(value,-30f,30f);
        yAxisValue = clampedValue;
    }
}

//Example Update
void Update()
{
    //Even when I pass 50f the value will be 30f because it is going through the property's set method
   //which will clamp it
    YAxisValue = 50f;
    transform.rotation = Quarternion.Euler(new Vector3(0,YAxisValue,0);
}

This will allow you to still modify the value through the inspector, and when changing the value through code just make sure to use the property YAxisValue instead of the field yAxisValue.

Hope this helps!

Thanks MacDx, sounds logical. I hoped I’d found a way to easily restrict it. Your property solution would work well though Many thanks for the help.