Unity2021: Properties

In this blog we will talk about properties. Its proper use is considered as a form of good practice and handled in the correct way will allow you to have better control over your variables when programming in C # for Unity.

1. Introduction

One of the good practices when programming using C # for Unity is not to make a variable public unless it is necessary, this to avoid that the variable is accessible for any Script.

To do this we can make our variable private, however, to control in a more adequate way the accessibility to certain variables we can convert them into properties which gives us control over what can or cannot be modified within a variable.

2. Creating a property

Let’s say we want to create a property for the private variable jumpForce (private variables start with lowercase), for this we must go step by step in defining the characteristics of the property that will encapsulate this variable:

  1. First we define the access modifier between private or public (depending on whether we want it to be accessible for other scripts outside of the current one)
  2. We define the type of variable among: integral (int), float, string, gameobject, …
  3. Name the variable (it is recommended something that does not lead to confusion with names of other variables in the future)
  4. Then we add those that will define the access to the variable, the accessors “get” and “set”

Then we define the variable to encapsulate, for this case is the private variable jumpForce and finally within the “set” brackets we define if the variable can be modified and how it will be modified.

3. Characteristic of a property

As you may have noticed, the “get” and the “set” are the ones that define how the property will be read and how the property will be modified, so if we subtract one of these two from our property, we can make it become a variable of write only (if we remove the “get”) or read only (if we remove the “set”).

This will give us control over who can access the variable and if it can be modified or not, preventing our variable from undergoing unwanted changes.

Properties also allow us to add functions or methods within them. An example of this can be seen in the image above.

Finally, a property can be self-implemented, that means that it does not require another variable or logic for its definition. To do this you must use the scheme shown in the image above.

As always thank you so much for reading our blogs!!
If you find this blog useful let us a comment, and follow us in our Instagram @tortugamedev and Twitter @Totuas2.
And don’t forget to check out the rest of the blogs about game development and our games!!

Leave a Comment

Your email address will not be published.