Unity Quick Tip - Setting private Fields through the inspector

Unity Quick Tip Set Private Fields in 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.

Creating a new 3D 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 PrivateField and double click on it in the Project panel to open it in Visual Studio.

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.

Private field not available to be set 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.

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.

Private field available to set in 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.

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.



Popular posts from this blog

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

Infinite Bounce - Unity Game Development Tutorial

Creating Terrain from Heightmaps - Unity Game Development Tutorial