Property
How to use properties when making classes in Unity.
Properties are used to read/modify (get/set) a variable without accessing it directly.
They are essentially two Methods merged into one concept. Because of this you are able to execute code before or after a variable is read/modified.
Properties avoid the need for dedicated getter/setter methods such as int GetMyInt()
and void SetMyInt(int targetValue)
, as required by other languages.
Why should I use Properties?
- To prevent a member variable from being changed directly.
- To error check before assigning a value to the member variable.
When should I use Properties?
- When an outside class needs to access a member variable.
Examples
Error checking
Properties can help us to stop member variables being set to the wrong value. In this example, _name
should not be empty, and _age
should never be less than 1.
Next, we’ve made the variables private, so no outside class has access. They can instead access the newly created properties.
Now, when a class sets Age = -20
, the Age property will run the code inside set
.
When a class sets int newNumber = Age;
, the Age property will run the code inside get
.
To add error checking, we must modify what happens when the properties are set
.