Unity Quick Tip - Setting private Fields through the inspector
It's generally good practice to make fields private if we don't want them to be changed from other scripts, but doing this means they aren’t available to be set from the Inspector. In this Unity quick tip we're going to look at how we can have the best of both worlds and have private fields that can be set through the inspector.
Let's get started by creating a new 3D project.
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.
Let’s add the following private field to the script.
private float someValue;
If we save the script and switch back to Unity, we can see that the field is not available in the Inspector.
If we switch back to the script, we can instruct Unity that we want the field to be available in the Inspector by adding the SerializeField attribute.
[SerializeField] private float someValue;
If we save this and switch back to Unity again, we can see the field can now be set through the Inspector.
By doing this we've created a field that can only be set through the Inspector or within the body of the script itself. No other scripts will be able to change this value.
Comments
Post a Comment