Properties are special methods which appear to be used more like Variables instead of being called like regular methods even though they are actually methods internally. They are defined using the get
and/or set
keywords like so:
Property | Equivalent Methods |
---|---|
|
|
Properties are very useful for validating input values or reacting to changes, for example:
public class Health : MonoBehaviour
{
private int _CurrentHealth;
public int CurrentHealth
{
get => _CurrentHealth;
set
{
// Treat any value less than zero as zero.
if (value < 0)
value = 0;
_CurrentHealth = value;
// Here we could update the health bar in the GUI or something.
// If the value is zero or less, destroy the GameObject this script is attached to.
if (value <= 0)
Destroy(gameObject);
}
}
}
Auto-Properties
You can define properties without a body for the getter or setter to have the compiler automatically create a backing firld for it, which is known as an Auto-Property:
Auto-Property | Equivalent Regular Property |
---|---|
|
|
In the above example, the property does not really accomplish anything and could simply be a public
field. However, it is possible to give the getter and setter different Access Modifiers (for regular properties as well) like so:
// Anything can get the value of this property.
// But it can only be set from within the declaring type.
// This is known as a read-only auto-property.
public int Number { get; private set; }
The Static section contains an example that makes use of read-only auto-properties.