Unity3D: Variables in C#

4 min readJun 3, 2022


Variables are like containers that can hold specific data that we can manipulate with code. There are many different type of variables within unity with the most common five being; Int,float,var,bool, and string.

Int stands for integer, and int variables can only hold whole numbers.

Float represents numbers with decimals. Float variables can hold both integer and decimal numbers.

A var variable is an omitted data type that becomes the data type that is assigned.

Bool or Boolean variable is a variable that contains True or False. It acts like a light switch. when the lights are on, the boolean is true. When the lights are off, the boolean is false. Its very useful for checking if something has occurred or not.

Lastly String, String represents letters. No numbers can be assigned(put in) into string values.

Variables In Action

Create a Script In Unity and name it AdditionDemo.

zoomed in pic

To declare variables we first type in the variable type then a name to associate it with. in this example, ill be adding two Integers. So ill create three variables; one named int1 ,the other int2, and the third Total. Int1 and int2 will be added in Int Total then displayed in the console.

It is important that the name of the variable is closely related to what the variable is being used for. Make the name obvious or have enough context to avoid confusion down the road.

The variables are declared, however they aren't assigned any values. So by default, they all equal to zero.

There are three ways we can do this in this demonstration.

we can use = to give them a value right then and there

I can assign them in Start() by referencing their given names.

I can set assign them in Update().

These both will do the same execution however there's a difference between how many times Start() and Update() executes those two lines of code.

Start() will only execute the code once when the script is first initialized.

Update() executes every frame that has passed. So if your game is running at 60 frames per second. The code will execute 60 times per second.

Side notes:

variables must be typed within the classes { } otherwise it will not be able to be processed through any of the attached namespaces or monobehavior.

From what I have seen, its standard practice to place all variables above.

I then add the two ints together and insure that the sum of the numbers is stored so that it can be used to be displayed in the console.

In this case Int1 and Int2 will be added and stored within Total.

Ill use print so that I can see the sum of the numbers in the console.

I place it in start so that it’ll only execute once since our code isn't constantly changing.

Ill create a game object and make sure the script is attached to a game object.

Once that is done, I will be able to see the sum of the two numbers displayed in the console. In this case, 2 + 3.





Unity Developer Based out of California