Using Variables in Unity — The Seeds of Beautiful Code

Christopher Pearl
3 min readApr 30, 2021

--

When it comes to programming in Unity, variables are everything! After using this object oriented language, I realized the power of Unity and creating incredible 2D, 3D, and XR experiences. Simply put, a variable is a box that holds information, and can be changed and substituted at any time. Every variable has a name (that I create and assign) after the variable is decided. Let’s dive in and go through the basics of what became and still is a vital and fun part of programming variables in C#.

There are quite a few variables that can be used in the language C#, but the variables I’ve commonly used are: int (short for integer; whole numbers), string, float (decimal, fractional numbers), and bool. Also, I use variables that are only used in unity to make my games functional like GameObject(the most popular), Animator, and Transform.

Each variable came across as a new super power when I applied it to my code in Unity!

My space shooter game was a great way to put my new found knowledge on variables to use.

Adjusting the speed of my Space Shooter, Code

There are 2 types of variables that I use in C#: Local variables and global variables. Local variables can only be used inside the method it is created for. The privatization of a variable is important when your game or app is being used. It can keep the user score or information from being noticed by other players, for example. Global variables are usually located at the top of your code, outside of the Start and Update methods.

Integer variables let you hold whole numbers as values in C# sharp. This was valuable when I had to record player scores on my games.

String variables allow you to print word statements and sentences on the console.

Float variables allow you to hold decimal numbers as values. This was a great use for calculating money values like how much to tip a waiter or measure how much I weigh!

Last but not least, Bool variables are used for true and false statements. They are usually used as conditionals in “if statements” in methods, but can be used as individual variables as global variables as well.

Variables can be powerful in so many ways! The more you use them in your Unity Games, the better you’ll understand their functions!

--

--

Christopher Pearl

Unity Developer, AR/VR Developer, Virtual Reality Product Manager for Micro Medical Devices Inc.