Variables! — The building blocks of programming

You can think of variables as boxes to store some information to be referenced and manipulated in a program. We can use variables for the speed of a player, the current score of the game, the remaining lives, the skin color and basically for any element that needs a value in our games.

Creating a variable in C#

In order to create a variable in a C# script in your Unity project you have to follow this syntax:

Ok, lets explain each element of this line one by one:

  • Access modifier: indicates where the variable can be used, public means that you can access from any script and private the variable can be used by code in the same class.
  • Type: following the analogy from the beginning of the article, before storing something in the box we have to define what type of thing you can put in it. In C# the basic types are int (whole number), float (number with decimals), string (set of characters) and bool (true or false).
  • Name: a label to identify your variable.
  • Value (optional): The information to store in your variable.

Basic operations:

To change the value you can use the assignment operator (=), and we can use the arithmetic operators (+, -, *, /) for different calculations:

Example

A Software Engineer passionate about game dev and interactive products with Unity. I consider video games to be the artistic expression of programming.