John is a fervent writer, gamer, and guitar lover. Former automatic-transmission repairer, welder and hobbyist game developer.
An array is a collection of data of a particular type that can be accessed using an index. It is particularly useful for storing information of a particular data type when you don’t necessarily know the amount of information you will need before-hand. For example, say you wanted to store a collection of integers. You could dedicate lines and lines of code to declaring each integer, giving each one a unique identifier that would allow you to access it at a later time. Or you could have a single array of integers and access each of your integers by simply passing an index value. Far more efficient, much easier to manipulate.
So let’s go over how to declare, assign variables to, and use an array in C#, and how this can translate to the Unity3D environment. For your convenience, I've also included a video version of this article below.
Using 1 and 2D Arrays in Unity3D / C#
In order to declare an array, you simply state the data type you want followed by square brackets, and finally the identifier you want this array to go by. Like so;
You may want to make your array publicly accessible, in which case you would qualify your declaration with a “public”, or you may want to ensure it remains inaccessible publicly, in which case you would qualify the declaration with “private”.
It’s not enough to simply declare an array, however. You have to initialise it. As someone who learned to code largely through looking at examples online and watching YouTube tutorials, it does seem that failing to properly initialise arrays is one of the more common mistakes that beginners make.
So, to initialise your array, you need set it as a new instance of your data type array with a specified size. You can do this with your initial declaration or later in your code. The latter is useful for situations where you need the array to be accessible class-wise (so you need it declared at the top of your code), but you don’t know how large it needs to be until you start running your code. So, to initialise an array of integers with a size of six, you would type;
Or if you wanted your declaration and initialisation separate...
You can also declare, initialise, and set your array at the same time by setting the values on declaration. The size of the array will be inherently determined by the number of values you put in it. For example...
...will give us an array of ints that is six long, and will already have the values set.
Once you have your array declared and initialised, and assuming you didn't assign variables at declaration as show above, it’s time to enter data into it. This is done very simply by passing an index into your array and then accessing it like an other variable. So, if we wanted to set the first item in the array to 9, we would type;
You’ll notice we used 0, not 1, as our index value. Array indexes start at zero, which is important when accessing the last index of an array; you would subtract one from the length of the array in order to get the last item in that array. For example, to set the last item of our array to 6, you would do this;
Looping Through the Array
Using our Length variable, we can loop through our array and set or access each of our items in just a few lines of code. The following snippet loops through all items in the array and sets their value to the same as their index, and then prints that value to the log.
Within the syntax of the for command you are creating an integer named “i”, declaring that the for loop will run while i is less than the length of the array, and that i will increment by one with each iteration of the loop. Notice we do not need to subtract one from array.Length. This is because we are looping while i is less than the length. Which will be true until i equals the length, so we will not go beyond the range of the array.
Read More From Owlcation
You can also loop through your array without using the Length variable by using the “foreach” command. In order to achieve the same results as above in this manner, you would type;
As you can see, the syntax of the loop itself is more simplified. We simply declare our data type (int) and give it an identifier (integer) and then specify the array we are going to loop through (array). However the lack of an inherent incremental value means that we have to create and increment our own, as we did with the “count” variable.
A two dimensional array can be thought of like a grid, or a list of arrays. You declare in the same way as a single dimensional array, but with a comma to denote that this array has more than one dimension.
It is perhaps easiest to visualise a two dimensional array when setting the variables at declaration like so;
As you can see, the multidimensional array can be looked at as a two dimensional grid, or a list of single dimensional arrays, each of which is three in length. In order to get or set the value of an array position, you simply pass in the horizontal and vertical index, similar to a grid or spreadsheet. So if we wanted to print the lower right hand variable to the console, we would type;
Remembering that the indexes start at zero so the maximum index is the length (3 in this case) minus one.
Using Arrays in Unity
Unity provides an automatic GUI solution to editing arrays in certain contexts through the Unity Inspector. There are two ways to get an array to be displayed in the inspector, you can either make it public (as shown above), or you can serialise it. This is how you would make a declaration serialised;
Whether public or serialized, arrays that are displayed in the inspector are automatically initialised, so you do not need to set the size and content of the array in your code, though you can if you wish. Having an array public isn’t exactly best practice, however, so it would be better to get into the habit of having your arrays private (and serialized if you need to edit in the inspector) and write a public function for modifying or extracting information from the array. This also allows you to keep complete control over how information going in or out of the array is handled.
If, for whatever reason, you need your array to be public, and that array is going to have a LOT of items (thousands or more), you do NOT want it to show up in the inspector, as it will cause Unity to hang for a long time and probably crash. In such a situation, you can keep your array out of the inspector with the following qualifier;
And, remember, these arrays would need initialising in your code.
Custom Class Arrays
Arrays can be made using a custom class as a data type by initialising in exactly the same way as shown above. The only difference is that if you want your array of custom classes to be shown in the inspector, you will need to make the class serialise. You do that by putting;
Above your class. So a complete script for creating an array of a custom class data type might look like this;
This would create an array of “SubClass”’s, which for now just hold some arbitrary information for demonstration purposes, that is visible and modifiable from the Unity inspector, but which would need pass through the SetValue and GetValue functions in order to manipulate the data in that array.
And that’s the end of this brief tutorial on how to initialise and use arrays in C# and Unity3D. I hope you found this useful.
© 2019 John Bullock