As you begin to work on your Unity journey you will begin to amass a large group of similar variables such as ints, strings, floats, bools, Game Objects, and other types of variables. In order to help make your code more readable you can collect them in data containers called arrays. Let’s look at how the Unity Scripting Reference on Arrays (here) defines them as “Arrays allow you to store multiple objects in a single variable.” that ‘s pretty straight forward.

Arrays are extremely fast but they cannot be resized so keep that in mind if you want to add additional items to an array. A List can allow you dynamically add variables to the container which we’ll cover in another post. So what’s an example of an array? Let’s show a quick one.

Above we have 3 arrays for player names, the contents of several gold bags, and projectile speeds. Then in Update() we’ll do a for loop to iterate over the contents of each array when the player hits space bar. It will then print the final result of each array, since an array is essentially a container of multiple variables of that particular type. You don’t have to define them in the code like I’ve done here you can do that for example in the Inspector like below. However that’s it, once the size is defined you cannot modify it. They stay that way unless you make a new array and transfer the variables over to it.

So to recap the structure of an array is as follows. You have the accessor modifier (this is public, private, etc) the variable type you want to use with open and closed brackets (int[], float[], bool[], string[], etc) followed by the variable name (superBigArray as an example) then you have it either declared in code or just create a blank array by declaring the size with = new type[array size]. An example of a blank array fully written out would be like this and then a declared array like in the code above or example below.

Blank Int Array

Declared Int Array

Arrays are useful simplifying your code, instead of having multiples of a single variable clutter up your scripts you can truncate them down into one easy to manage variable. This is particularly useful if you are trying to organize groups of values such as int, floats, or even Game Objects. They do have limitations in that they can only be defined once at the start of the game and cannot be dynamically resized. For that reason Lists are typically what people prefer despite their larger overhead as the cost is negligible compared to the benefits. Until next time, happy coding.