Much like arrays, Lists are used to group collections of variables and objects. Unlike arrays which are static once created and can only be changed by creating a new array and copying over the values. By contrast lists allow you to dynamically add and remove values on the fly. This of course makes lists the go-to method for inventory systems, tracking groups of enemies, or any other dynamically allocated groups of data.
Let’s look at an example of creating a list. Head over to one of my favorite C# resources, Dot Net Perls (here) and look at the page on Lists. The basic structure of a list is as follows.
List<Type> variableName = new List<Type>(); is how you initalize the List like above for type Part from there you can use .Add() and .Remove() to respectively add and remove Part objects to the list. Unlike an array, a List is dynamic and can grow or shrink as needed. This costs more performance overhead but gives you greater versatility and doesn’t require making a new array everytime the values change.
In the script below we have a list of robots that we randomly remove one at a time and then print the remaining list when we hit the R key.
First we initialize the list as string then populate the list in the Inspector finally check to see if it’s null otherwise we print out every robot model in the list by iterating over the list in Start(). Then in Update() we check if the R key has been hit then once again check if robotModels is null (in case) and then set a randomIndex to a number between 0 and the number of entries in the list using Count. Then we remove one entry from the list and then do another foreach loop where we iterate over the remaining models in the list and print them out.
As you can clearly see Lists give you an efficient way to keep a group of objects together in a neat package. If performance was no issue I would whole-heartedly recommend them to be used everytime without hesitation. Unfortunately given the performance constraints of mobile platforms at the time of writing it is good to use them judiciously. Mixing them with arrays when and where it makes the most sense. Until next time, happy coding.