Variables: The Building Blocks of Programming
A brief look at how to create variables and how essential they are to successful programming.
If you want to learn to code, you need to what variables are. Variables are like boxes that hold data or values that you can use and change in your code. In this article, I’ll show you how to make variables and why they are essential in coding.
What is a Variable?
A variable is a name that stands for a value or data in your code. For example, you can make a variable called “name” and give it the value “John Doe”. Then you can use the variable “name” instead of the value “John Doe” in your code.
Variables can be of different data types. The kind of variable tells you what kind of data it can hold and what you can do with it. Some data type examples are numbers, words, true or false, lists, etc.
How to Create variables
Creating variables can differ slightly depending on what language you are using to code. Here we will focus on C#, the primary language used in Unity. Every variable needs three main elements, with an optional fourth as follows.
- Declare if the variable is private or public
- Enter the data type of the variable
- Give the variable a name
- (optional) give the variable a default value
For example,
Why are these essential?
Nothing in a video game exists without a variable. Health, Score, Ammo Count, weapons, etc. Every one of these is a variable created using code and told how to react or interact with everything else in the game. Pretend you have collected a nice bounty and you want to spend your hard-earned gold. First there is a variable called “gold” and every time you find a piece it gets added to a pool, another variable we’ll call “wallet”. The wallet holds gold you have collected. Gold=1, you find 15 gold. Your total gold now equals “current wallet balance” + gold * 15. Now let’s say we now have 275 gold. We are looking at a shiny new sword that costs 240 gold. When this item is purchased your wallet balance updates, “new wallet balance” = “current wallet balance”(275) - item cost(240). Your “new wallet balance” is 35 gold.
Summary
This is all controlled using variables and telling the program what to do with them. As you can see, these are the true building blocks of programming. Nothing exists without a variable. They allow us to store, manipulate and access data in our programs. By understanding how to use variables, we can create more dynamic and interactive programs that can solve various problems and tasks. As well as more immersive video games and movies. In my next article we’ll talk about Pseudo Code: Why?