C#: Arrays

November 3, 2023

In game development, using arrays can help you to organize your data and to improve your game’s performance. This article will teach you everything you need to know to get started with using arrays in C# with Unity.

What is an array

An array is a collection of elements of the same type. The number of elements in an array is called the length of the array. The length of an array is fixed - you cannot increase or decrease the number of elements in the collection.

With non-collection types, you may declare one instance of each variable like enemy0, enemy1, and enemy2.

With a collection type, you declare one instance of the collection, like enemies, then record variable instances within the collection.

For an array, you record the variable instances by index: enemies[0], enemies[1], and enemies[2].

Naming an array

The .NET Framework style guide recommends that you name arrays using the plural noun.

For example: Prefer enemies[] over enemy[].

Declaring an array

To declare an array, write the type, then the brackets, then the name.


GameObject[\] enemies;

In this case, you have declared the array. But, you have not initialized it. If you try to use it, you will get an error.

Initializing an array

To initialize the array, you need to create a new instance of the array.

To initialize the array, you have two options. You can either initialize an empty array, or you can initialize the array with values.

Initialize an empty array

When you create a new empty array instance, you must pass in the length of the array.


GameObject[\] enemies = new GameObject[5\];

This array is populated with the default value for the type. For GameObject, this default value is null.

Initialize an array with values

To initialize an array with values, you wrap a comma-separated list of the type in curly braces.


GameObject[\] enemies = { enemy0, enemy1, enemy2 };

Accessing an array

To access the value of an element from the array, index the array name.


GameObject enemy1 = enemies[1\];

Iterating an array

Using a For loop with an array

To iterate an array, you can use a For loop.


for(int i = 0; i < enemies.Length; i++)

{

Debug.Log(enemies[i\]);

}

Using a ForEach loop with an array

You can also use a foreach loop to iterate an array.


foreach(GameObject enemy in enemies)

{

Debug.Log(enemy);

}

When to use For vs. ForEach

You should use the For loop when the indexer is an important part of your loop.

You can prefer the ForEach version when the indexer is not crucial to the functioning of your loop.

Want to build better games?

© 2024