Arrays in Unity

addam davis
3 min readJun 15, 2021

--

Objective: Basic understand what an array is and how to implement into code.

Arrays allow you to store multiple objects into a single variable. The Array class is only available in Javascript.

There are three ways to write an Array.

Declare the size (how many elements) through the inspector

the first method you need to save often, if Unity crashes you will loose the information you manually entered.

The number of elements is determined in the code.

The second method is the same, if you change the size or the information contained you will loose said information if Unity crashed, unless you save after you edit the information.

specify in code what the values are

Hard coding

The third method is the safest from crashes because the information is hard coded in Unity. If Unity crashes the information will be filled in via the code.

If you wanted to print out an element you would use the Debug.Log

First fill out the elements with what ever you need.

Then use the debug.log with the number of the element you want.

In Unity numbers start at zero, so three is the fourth in the list.
The name Caron is displayed

If you wanted to randomize the element that is displayed you can use the random.range function.

Now, it will print out Caron with a random item.
Carol fish. the random element was 1

Using arrays we can use call upon multiple elements, such as an inventory system or many other functions in your code. Don’t be afraid to experiment with your code, and I’ll see you in the next tutorial.

--

--