Unity C#: Lists
Objective: Use lists to add objects to scene and at ten turn them green.
A list is like an array, but are dynamic, i.e. the size can vary. To start, create an empty object and name it Game_Manager. Add to it a GameManager C# script. The first list, _prefabs, will contain a list of prefabs which will be assigned in the inspector using SerializeField. The second, _objectsCreated, will be created dynamically. The bool _spawnEnabled is initially true and used to control the spawning of objects.
Go ahead and create a 3D Object > Cube, Sphere and Capsule. Create an new folder called Prefabs in the Assets folder of the project and drag these new objects into the Prefabs folder. Delete these objects from the hierarchy window. Now assign the _prefabs using the inspector as shown.
In void Update() user input is checked for the space key being pressed and provided _spawnEnabled is true selects a new random Vector2 pos for the new object between -10 & 10 on both the X and Y axis. To be able to see these newly spawned objects set the Main Camera’s Z position to -20. The prefab is randomly selected from the list of _prefabs using the _prefabs.Count, which is the list equivalent of Length. Lists use the Add method to append objects to the list, in this case the object is instantiated at the same time that it is added to _objectsCreated. Next the length of the list or Count is checked to see if it has reached 10, and if so cycles through each object in the list to change the color on the MeshRenderer’s material to green. In the example below, the list is then cleared and _spawnEnabled set to false.
To remove objects from the list, delete _objectsCreated.Clear(), and add to void Update() a new if statement that checks for the “R” key being pressed. A random object from the _objectsCreated list is then selected. This object is destroyed then removed from the list, as shown below. The _spawnEnabled is reset to true to allow new spawns.
Because of their dynamic nature, lists are a powerful way to manage items, enemies and even players in a game.