Unity Quick Tip - Assigning a Range to a Field
In this Unity quick tip we'll look at how we can set a range for the number fields in our scripts.
You can either watch the video version below or continue reading for written instructions.
We’ll add a new script to the Main Camera by selecting it in the Hierarchy, clicking the 'Add Component' button in the Inspector, and then searching for the script component.
We'll call the new script Range and double click on it in the Project panel to open it in Visual Studio.
Let’s add the following public float field to the script.
public float speed;
If we save the script and switch back to Unity, we can see that the field is visible in the Inspector and we are free to type any value.
If we now switch back to the script we can use the Range attribute to set a minimum and maximum value for the field.
[Range(0, 10)] public float speed;
If we save this and switch back to Unity we can see that the free entry textbox for the field has now been replaced with a slider that lets us set a value within our specified range.
That covers everything for this tip. We hope that you found it useful. Please leave any questions or feedback in the comments below, and don't forget to subscribe to get notified when we publish our next post.
Thanks.
Comments
Post a Comment