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.


To demonstrate this, we’ll create a new 3D Project.

Creating a new project in Unity Hub

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.

Adding a 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


Entering number value in text box

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.

Assigning a value using the slider

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

Popular posts from this blog

Rotating a Character in the Direction of Movement - Unity Game Development Tutorial

Changing the Colour of a Material - Unity Game Development Tutorial

Creating Terrain from Heightmaps - Unity Game Development Tutorial