Variables — The Bread and Butter of Programming in Unity

Ethan Bristowe
3 min readApr 25, 2021

--

Think about what makes up some of your favorite games. Maybe your score? a health bar? How about ammunition for a gun? What about the gun itself? These are just a miniscule set of examples of what are called variables. Nothing in a game can exist without a variable being created for them. It’s arguably the most important thing to learn, when learning to program. So, let’s begin!

Part 1:

So What Even is a Variable?

A variable in the simplest terms, is a box… a box that is defined by what’s in it. And you can put pretty much anything you want in there. Be it numbers, words, or lists to name a few. These boxes will store this information for you to access whenever you want, from wherever you want. And once you access a variable, you can change, save, delete them, you name it. Variables are the building blocks of programming in Unity, nothing could exist without them!

Part 2:

Variable Data Types

Ok, variables are great blah blah blah, let’s get into the nitty gritty now, yeah?

Every variable needs a data type, it defines the type of information that the variable holds. The four most popular data types are

  1. string: Contains letters and words
  2. int: Contains integers
  3. float: Contains numbers with a point value
  4. bool: Contains true or false values

Here’s an example of what these data types could be used for in a RPG game:

Part 3:

Public or Private Variables

All variables need to be classified as private, or public. A private variable can only be accessed within the script that it resides in, a public variable can be accessed by other scripts outside of it’s own.

Here’s an example of what variables in the RPG game we would want public or private:

Our playerName is public because we would want other players to be able to see our name.

Our health is also public because we would want enemies to be able to deal damage to us, and decrease our health variable.

Our sprintSpeed will be set to private because I don’t want any other scripts to change it.

And lastly our isAwake is a private variable because no one but the player should be able to decide if they will want to sleep or not.

These were only a handful of the most common data types, and only a few examples of their use cases. I hope this article showcased just how endless the possibilities are when using variables, and just how important they are when programming in Unity!

--

--

Ethan Bristowe
Ethan Bristowe

Written by Ethan Bristowe

Passionate self taught game developer excited to learn and share everything I can about game development!

No responses yet