C# Properties In Unity

What are Properties?

Properties are variables that posses additional functionality beyond storing data. Properties can explicitly be written to or read from, can contain conditional statements, and perform function calls.

Example of a basic property

the structure of a property:

Public int PropExample { } being the property itself. it’ll act like a variable since theres no code populating either get or set.

Get{} and Set{} are called Accessors. As the name implies, they control how one may access the property.

Get{} allows us to get the variable. ie use it in another variable or function to retrieve int PropExample value (which is set to 0 be default).

Set{} allows us to assign Int values to it. The PropExample = value ,insures that it assigns it the proper data type, in this case an int.

Another note is that properties can be explicitly made to be only read or written. Properties can be set to only have a get{} or a set{}. get and set can also be made private so that only the script itself may access those accessors.

Properties also come in another flavor. Instead of the structure above they can be written like this.

Public Int PropExample{ get; set}

This is called an auto property.

Demonstration

Creating a Experience and Level up system using one Property. When the user Presses Spacebar, 10 is added to Experience property. When Experience equals to Levelup Lvl will increment and Levelup will be assigned the current value of Experience plus 25. The amount of experience needed to level up increases as the player becomes more powerful.

Input for Demo

Value refers to the current value of float Experiance.

Since we are constantly adding or ‘setting it’, it’ll trigger whatever we code into the set portion of the property. In this case our conditional statement to handle the level up and experience scaling.

Conclusion

Properties is another way to execute logic that could have been otherwise be called from a function. The advantage of this is that it cleans up code. A more important aspect of properties is that it can discriminate on what part of the property may access it.

--

--

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
Vixian Phimmasone

Vixian Phimmasone

Unity Developer Based out of California