What are Arrays and Lists?
Exploring collections in programming is essential for handling data efficiently. In this module, we will delve into two key structures: Arrays and Lists. Both are fundamental to development, especially in environments like Unity, where data is constantly being manipulated.
How are Arrays used in Unity?
Arrays are fixed data structures ideal for storing collections of data of the same type. They are ideal when you need to handle a known set of elements that will not change size during program execution. Here we show you how to define and use an Array in Unity:
public int[] Numbers = new int[2];
This Array is initialized with a size of two elements, which you can view in the Unity Editor. To traverse an Array and process its data, you can use a for each
loop, as shown in the following example:
public int[] count;
void Start() { foreach (int item in count) { Debug.Log(item); }}
By adding items in the console, you will be able to observe how they are printed, thus exemplifying how they work in Unity.
What are the advantages of Lists?
Unlike Arrays, Lists are dynamic data structures that can expand or contract as you add or remove items. Here's how to define a List in C#:
List<string> names = new List<string>();
It is crucial to initialize the List, even when you have a constructor, using new List<string>()
. Lists are especially useful when you need to handle real-time dynamic data, such as scoreboards or lists of players in a game.
You can add elements in the following way:
names.Add("Pablo");names.Add("Pedro");names.Add("Anita");
The procedure for removing elements is just as simple:
names.Remove("Pedro");
And to go through the List, a for each
can also be used:
foreach (string name in names) { Debug.Log(name);}
When to choose Arrays over Lists and vice versa?
The use of Arrays or Lists depends on the context:
- Arrays are excellent for fixed-size data and when looking for space efficiency and access speed.
- Lists offer flexibility and are ideal when the size of the data set is unknown or variable.
Both structures are powerful programming tools, facilitating data management and manipulation in game and application development. Their correct implementation not only improves code efficiency, but also enriches the game experience. We invite you to explore more about collections and their applications in development, keep learning! In the next class, we will delve deeper into dictionaries.
Want to see more contributions, questions and answers from the community?