Properties - C# Skill in Unity: 4

Objective: learning how to use properties in Unity.

Properties is a great tool when creating manager classes in Unity. We have had used properties in many ways, such as setting position to gameobject or receiving time from system. These are all properties that already written in the system.

Getter and setter

To set a property, first we need to declare a private variable.

Then create a getter setter property with this variable.

Get” is the place to return the value of this property when user trying to receive it.
Set” is where user can change the value.
And it should looks like this after fixing.

Now we can test it in Start(). When you try to use WalkingSpeed, it should pop up the hint of this property.

Get but not set

We can also make this property as read only, by simply remove the “set” part out of it.

Since we have not giving it the value, you might need to set the value to the variable, otherwise it would only return zero in this example.

Now if we test again by calling it in script, it should reveal as get only.

Auto properties

We can also simplified the setting of property, which is called an auto property.
To create an auto property is simple, just set the property without declaration of variable.

Now the property is simplified to one line of code, and we can still call it in script.

However, if we need to set this property as read only, we can also remove the setter. What’s better, we can set the setter as a private set. This would allow the value of it can be set by this script but not changeable by other scripts.

And this would also reveal in script.

You can call and change this value from a public method of this script.
It is really helpful to manager classes.

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
S.J. Jason Liu

S.J. Jason Liu

99 Followers

A passionate gamer whose goal is to work in video game development.