GetComponent

Hi guys, I hope you are fine. I have an interesting question :D. I am watching course video right now and I want to ask my question ASAP. In this course we are trying to add path to our list which is “List path = new List();” (WayPoint is a class). We get all game objects by using this code "GameObject wayPoints = GameObject.FindGameObjectsWithTag(“Path”); " and we add these game objects to our list with this code “foreach (GameObject waypoint in wayPoints)
{
path.Add(waypoint.GetComponent());
}”
My first question is why we cannot use path.add(wayPoints) instead of using “path.Add(waypoint.GetComponent());” and how does this code actually work ?

thank you in advance :smiley:

Hi @_Tolga,

Welcome to our community! Those are indeed interesting questions. :slight_smile:

  1. The Add method expects one object, not an array of objects. That’s why path.add(wayPoints) will not work and why we have to use a foreach loop. See here. We call GetComponent because we are interested in the Waypoint objects, not in the GameObject objects.

  2. Most of us do not know that because we use C# to make our lives easier. In the end, our code gets translated automatically to machine code. If you just wanted to know what the Add method does: It adds an element to the List object referenced by path.

Did this clear it up for you? :slight_smile:


See also:

1 Like

Thank you for this clean explanation !. I always ask interesting questions like this :smiley:

This topic was automatically closed 24 hours after the last reply. New replies are no longer allowed.

Privacy & Terms