Variables! — The Building Blocks of Programing

A variable is a location where information is stored that can be accessed and used by your program.

There are several types of variables and they are:

  1. int - a whole number that can be positive or negative. eg. 7
  2. float - a number with decimal places. eg 7.11
  3. bool - a true or false condition. eg. false
  4. char -is a single character, it can be a letter, a number or a special character. It is written with single quotes. eg. ‘b'
  5. string -can be letters, numbers or other characters in the form of words or sentences. It is written with double-quotes. eg. “my name is:”

The variables can be private or public.

Private variables can only be used in the script they reside. A naming convention to use with private variables is to prefix them with an underscore. eg. private int _speed;.

Public variables can be shared and accessed from other scripts.

To declare variables use the following syntax:

<private or public><variable type><variable name>

eg. private int _age;

Ok now that we know what variables are and how to write them, let’s look at some real-world applications

You want to keep track of your player’s health or maybe coins collected. First, we need to decide if it will be private or public. In this case private. The next is what type will we need. In this case, I would use int, because we are dealing with whole numbers. Health 0 to 100 or coins in increments of 1.

Here is what that looks like

Next, you may want to control how fast your player can shoot their weapon. This will require 2 variables a float and a bool. The float will be used for the fire rate as that will have decimal points. The bool will be used for the can fire, this will be either true or false.

Here is what they look like

One last tip on variables, if you want to be able to change the value in the inspector while testing your game, you add a serialized filed attribute. here is how you add it to your variable.

Happy Coding!



Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store