Understanding the "foreach" loop

Hello!

Just watched the lecture where we learn about using the foreach loops for the first time.

        foreach (Transform child in pathPrefab.transform)
        {
            waveWaypoints.Add(child);
        }

My questions are:

  1. Does the name “child” affect what is being retrieved from pathPrefab?
  2. If not, by writing “in pathPrefab.transform” it knows only to get the children?
  3. If I wanted to get the transform of the pathPrefab GameObject itself in a “foreach” loop how would I do it, or would I never use a “foreach” loop for this situation?
  4. Off of that, if I wanted to get the transform component from both the pathPrefab AND its children, how would I write that?

Sorry if this is an overwhelming amount of questions…

Hi @rods012,

Thank you for your questions.

  1. Does the name “child” affect what is being retrieved from pathPrefab?

The name does not affect anything. You could rename the variable to blah, abc or cats, and the loop program would still work.

  1. If not, by writing “in pathPrefab.transform” it knows only to get the children?

Yes, because that’s how the Unity programmers defined it. See the description of the Transform class in the API.

  1. If I wanted to get the transform of the pathPrefab GameObject itself in a “foreach” loop how would I do it, or would I never use a “foreach” loop for this situation?

Why would you want to access the Transform object of the pathPrefab in this(?) foreach-loop? pathPrefab.transform references the Transform object of the game object referenced by pathPrefab.

  1. Off of that, if I wanted to get the transform component from both the pathPrefab AND its children, how would I write that?

I’m not telling you the solution directly because I believe that you are able to find it yourself based on what I wrote in answers #1 to #3. If not, please let me know. :slight_smile:

Have your questions been answered?


See also:

2 Likes

They have Nina! Thank you once again! :smiley:

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

Privacy & Terms