Quick Tip: Using Properties on the Unity Inspector
Published a month ago
How to use one of the most popular c# feature with the Unity inspector.
First of all, if you are still not using properties, stop everything and learn how to use them.
Using it has a lot of benefits, ranging from enforcing functionalities from attribute changes, to creating a robust library that can last many version changes.
Although the usage of properties is wildly accepted in software development, it isn't used a lot when dealing with Unity development because the Unity Inspector doesn't directly support it.
Well it isn't his fault, properties are functions and exposing a function on the inspector doesn't make a lot of sense.
So how can you take advantage of the power of properties on unity? One easy way is using the OnValidate function.
Consider the following snippet of code:
// What gets exposed on the inspector [SerializeField] private int gameScore; // The Property public int GameScore { get { return gameScore; } set { if(value < 0) { value = 0; } gameScore = value; } } private void OnValidate() { GameScore = gameScore; }
Here we decided that our game score variable couldn't have its value being less than zero. So we added the if statement on the property and kept the gameScore variable private to the class.
But we might still want to acess the variable trough the inspector, so we add the [SerializeField] and the OnValidate porting of your code.
With those two, whenever you change the gameScore value trough the inspector, the OnValidate function will run and change the value accordingly.

Pedro Azevedo
Indie Developer - Programmer