Arrays

Discover how to store and access multiple values of the same data type using index-based notation with arrays.

Introduction

Arrays are a fundamental data structure in C# that allow us to store and manipulate collections of values. Here’s a brief introduction to arrays and some tips and best practices for working with arrays in Unity.

What are arrays?

An array is a collection of values of the same data type, stored in contiguous memory locations. An array uses an index to identify each value’s position within the array, and it can store any type of data, including numbers, strings, and objects.

Here’s an example of how to create and use an array in C#:

Press + to interact
int[] numbers = new int[5];
numbers[0] = 10;
numbers[1] = 20;
numbers[2] = 30;
numbers[3] = 40;
numbers[4] = 50;
for (int i = 0; i < 5; i++) {
Debug.Log(numbers[i]);
}

In this example, we’ve created an array called numbers that can store 5 integer values. We’ve then assigned values to each index in the array using ...