Variables
Variables are the building blocks of games. Everything in game doesn’t exists and must be created by the developer and in the creation of the different components that make up a game, wouldn’t be possible without variables.
What are variables? Variables are like school lockers, where you can put things into them to store and get things out when you need them. When creating variables you will need three things with an optional fourth.
- You need to declare if the variable will be public or private
- You need to specify what type of variable it will be
- You must give it a name
- Optional: Give it a value
What is the difference between public and private variables? Making a variable public will allow other gameObjects the ability to access it, which is extremely useful when you want scripts to communicate with each other. Also, a public variable appears in the Inspector, allowing for a Game Designer to make real-time adjustments without having to change the code.
A private variable does the opposite of that by only allowing the gameObject that the script is attached to have access to it. Sometimes you want a variable to be private, but want it to appear in the Inspector too, so Game Designers can make adjustments without altering the code or script. Using a [SerializeField] with a private variable keeps the variable private, but allows it to appear in the Inspector. It is the best of both worlds!
There are many different variable types, but we are going to focus on the big 4 and how I plan on using them in my Space Shooter 2D game (I need to come up with a better title).
- String
- Int
- Float
- Bool
A string variable is a going to hold text information and in my game I plan on creating a Leaderboard to mimic classic arcade games, where players would input their 3 initials or other clever 3 lettered words if they have achieved a top score. Right now this is a private variable, but I may have to make it public so a Leaderboard script can have access to it.
An int stands for integer, which is a whole number. This variable is helpful when you know you will be dealing in whole number, and in my case, the Player’s score will be stored in this variable. It is public because it will probably need to be accessed by a Game Manager or Leaderboard script.
A float variable is handy, when you need a decimal number. I am using float variable for the Player’s speed. This is a private float variable because other gameObjects do not need, only the Player, but used a [SerializeField] so a Game Designer can easily adjust the Player’s speed in the Inspector.
Lastly, a bool which is short for a boolean variable. This is variable that has two states (true or false, yes or no, 0 or 1). A boolean is the perfect variable to use for Power Ups in my game because it is either the Player has a power up or they do not.