Encapsulation is one of the most pivotal aspects of coding. In a nutshell it is the ability for classes to keep parts or all of themselves private unchanged from the outside. However sometimes these private variables must be changed from the outside but otherwise hidden away. This is where Properties step in. These are super handy advanced variables that helps you maintain scope in your projectile while providing extra functionality when variables are accessed.
So how do they work exactly? Let’s take a look at a simple example.
So here we have a string field named name and then we create the property itself named Name. The camel case is important as it tells you that it’s a property. Then within public string Name we have a getter and setter. The getter simply returns the private value name to whatever called the Name property variable in this example. The setter however changes the private variable to the value. It is important to note that the private variable is never touched directly, only when a setter is called through the property. No (or public ) setter, no chance of changing the value outside the class. An important caveat is that properties do not show up in the Inspector so keep that in mind.
In addition to standard Properties there are Auto Properties, these are short hand properties. This is declared like a normal public variable with Pascal Case and curly braces with get; and set; inside of it. Here’s what it looks like.
Much shorter, sweeter, and easier to read but functionally they’re perfectly identical. It is important to remember to that both get; and set; need to be used in auto properties.
You’re probably wondering “Ok great, these seems nice so when do use these things?” There are a few reasons to use Properties over standard variables. You need fine grain access modifier control, it’s entirely possible to make a set private and a get public. You could track all access to a getter to see who access it and setting breakpoints to debug at the setter value. In addition to the added benefit of running functionality when the added is grabbed or change like below.
As you can see properties bring a lot of versatility while enforcing encapsulation to your variables. They do add a bit of overhead to your performance and are hard to see due to not serializable in the inspector. Despite that they help enforce modularity of your code and make variables more extensible. Ultimately they another tool in your toolbox, until next time happy coding.