Private vs Public Variables

David Hunter Thornton
3 min readAug 7, 2022

--

What’s the difference between public and private variables?

Objective: Explain how to write a private variable and the ways it interacts with Unity.

We just finished discussing all of the basics of variables in my last article. For that article we wrote a public variable and made adjustments to the numerical value inside the Unity Inspector. Now let’s talk about private variables.

We’ve already got a public variable written. But since public variables can be accessed by any other script, its more resource intensive, and generally, you just don’t want everything as public anyway.

You’ll see that I’ve done two things in the above. Changed public to private — that’s the easy part. And add an underscore in front of the speed variable name. This is the industry standard for any time you write a private variable so that its easily seen as private anywhere in your code.

However, as you can see, I had to change it in both places. As your code gets more complicated, it can cause errors if you forget one of the places a variable’s name is located. There’s an easy solution for this.

Here I’ve selected the name, Visual Studio searched for the name everywhere else in the script and selected that as well. I then simply “Right-Clicked” and selected “Rename”. This allowed me to change everywhere the variable’s name exists all at the same time.

Now if you save this new code and open Unity, you’ll see that you no longer have access to change the variable’s value of 4.5 anymore. But let’s show off another cool feature of C# and Unity.

By adding “SerializeField” inside square brackets we’ve told Unity that we want an editable box/line in the Inspector for this variable. Now when we return to Unity, we can edit the speed again without ever opening our code.

An important question to ask, is “When should I use public or private variables?”.

If the variable you’re writing needs to be accessed by another script or mechanic, (for example Health) then you should use a public variable. This allows other enemies to damage your health, items to heal your character, or gear to increase your health.

All of these things exist somewhere else in our project, but need to be able to find and manipulate the base health that we coded in. If it’s something static that will never change, or something that doesn’t need to “talk” with any other mechanic in your game, those should be private variables.

Friendly Reminder: Don’t forget to keep updating your project through GitHub/Git and saving any changes you make to a separate branch. You can check out my other articles to get a breakdown of those steps! Day 1–9

--

--