Yes, and no, a List<>
, as the one created in the project (there are other types of lists), can contain objects of a specified type, that the yes part, Which objects it contains? The ones you put in it. Lists are null
by default, and new
lists are empty until you put something in them.
I’ll explain further.
[SerializeField] List<Waypoint> path = new List<Waypoint>();
This line of code creates a new list that can hold objects of the type Waypoint.
List<Waypoint> path;
The line above would throw an error because that variable is null, it doesn’t have a list, yet, you have to create the list with the keyword new
, just as Gary did.
If you leave the list as in the first example, the one I took from the course, you can see that it is empty in the inspector. To populate it Gary searched for every object with the tag “Path”, and then added it to the list.
void FindPath()
{
path.Clear();
GameObject[] waypoints = GameObject.FindGameObjectsWithTag("Path");
foreach(GameObject waypoint in waypoints)
{
path.Add(waypoint.GetComponent<Waypoint>()); //Here
}
}
He’s not looking for the Waypoint
component, he’s looking for the tag, that’s why you need to use the GetComponent
method so that you can add them to the list, otherwise, it wouldn’t work, you can’t add objects that aren’t of the same type as the one the list wants.
I’ll give you an example using the Transform
component in a few hours.