Variables — The Building Blocks of Programming

Austin Hall
2 min readAug 25, 2022

--

think of a variable as box that contains information. what kind of information contained in that box is up to you. To create a variable there are three required components with an optional fourth.

  1. A public or private reference: Public means you can see it and manipulate it in the unity editor, private means that only the script has control of it.
  2. Data type: this is what actually defines the variable. the most common types are string, Boolean, floats and integers.
  3. Name: every variable needs a name
  4. Value: this can be done when the variable is created or it can be assigned later during a specific operation.

why do we need variables? Lets take a look at a script using a variable for speed.

Movement script using a variable to control speed.

In the script above, we have an object that is set to move up at a given speed over time when the spacebar is pressed. Would it make sense to just put the number 10 into that code instead? Short answer, no.

this code is for a laser shot from a player object. What if I wanted to have a power up in my game that increased the rate of fire? I would have to go back to every instance that I typed this line of code and adjust it manually. using the speed variable, I can reassign the value in another method and it will adjust that variable for every applicable instance.

If we take a look in the Unity Editor, we’ll see something cool. we can actually see the speed variable and manipulate it inside the editor. It is important to note that if we change the variable value in the editor, it will override the preset value in the script.

--

--

No responses yet