A Quick Introduction to Arrays in Unity

Dennisse Pagán Dávila
3 min readAug 9, 2021

--

What is an Array?

An Array is a variable that holds multiple values of the same type. As such, they are commonly used to organize data to make it easy to sort and easy to search through.

For example, a list of student names which all go in the same file.

Syntax

The syntax of an array can be easily remembered by its square brackets. The type of variable within the array always goes before the square brackets as a way of saying “This is the type of data that will go in this box”, followed by the label or name of what it contains.

There are different ways to declare an array, you can set the size of the array and values directly through code, or you can make use of the Inspector to manually add values.

Array Declaration Examples:

Assigning Values in the Inspector

In Unity, we have the unique ability to assign the contents of an array through the Inspector. This makes adding any number of data easier and more dynamic. In this case, you don’t have to set the size of the Array in code since you are able to keep adding data manually through the Inspector.

Note: Bear in mind that you will need to make the array public or private with a SerializeField in order to access it from the Inspector.

Using the Inspector to Assign values is as simple as clicking the plus icon in the newly created array section of your script component and adding any pertinent data you like.

Accessing Elements in an Array

The contents of an array are organized as index numbers or elements that start their count from the number 0.

Each individual element can be accessed by their respective number as follows:

You can print the value in the console view:

You can also print out or access all the items on an array by using structures like a for Loop or a Foreach Loop

In the next article, I’ll be taking a look at for loops!

--

--

Dennisse Pagán Dávila
Dennisse Pagán Dávila

Written by Dennisse Pagán Dávila

Software Engineer that specialize in Game Development. Currently looking for new opportunities. Portfolio: dennissepagan.com

No responses yet