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.
public class Human : MonoBehaviour {
public string _name;
public int _age;
void Start()
{
// These errors will not be picked up
_name = "";
_age = -20.
}
}
Next, we’ve made the variables private, so no outside class has access. They can instead access the newly created properties.
public class Human : MonoBehaviour {
private string _name;
private int _age;
void Start()
{
// These errors will not be picked up
Name = "";
Age = -20.
}
// Property
public string Name
{
get { return _name; }
set { _name = value; }
}
// Property
public int Age
{
get { return _age; }
set { _age = value; }
}
}
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
.
public class Human : MonoBehaviour {
private string _name;
private int _age;
// When the game starts
void Start()
{
// These errors will be picked up, so member variables will not be set to the wrong values.
Name = "";
Age = -20.
}
public string Name
{
get { return _name; }
set
{
// If the value that we are trying to assign to _name is empty
if (value == "")
{
Debug.Log("Error: Name cannot be empty!");
}
else
{
// Apply value to member variable
_name = value;
}
}
}
public int Age
{
get { return _age; }
set
{
// If the value that we are trying to assign to _age is less than 1
if (value < 1)
{
Debug.Log("Error: Age cannot be less than 1!");
}
else
{
// Apply value to member variable
_age = value;
}
}
}
}