Help me understand this part of the Foreach loop

I’ve been stuck for four hours trying to understand lecture 98. Using A Foreach Loop, and this is what I got from it.

What we’re trying to do is move the process of reading waypoints from the enemypathing to the waveConfig script, correct? but the list of waypoints in the enemypathing script, cannot connect with a method of type GameObject and it will produce this error

  void Start()
    {
        Waypoints = waveConfig.GetpathPrefab();

        transform.position = Waypoints[waypointIdex].transform.position;
    }

it has to be a list of type transform, so we change the the public method in the waveConfig to the following:

public List<Transform> GetWaypoints()

now this public list will return a wavewaypoint, and this wavewaypoint will be a variable of new list of type transform like this:

 public List<Transform> GetWaypoints()
    {
        var waveWaypoints = new List<Transform>();

        
        return waveWaypoints;
     }

Then, we get to the confusing part. We decided to use a foreach loop, and what the loop does is iterating over the Transform object that is assigned to our pathPrefabs, in this case, the waypoints, and we will name them child.

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

What I don’t understand is what is the function of waveWaypoints.Add(child) or what does it mean for the loop, and why did we identify it as a variable of new list of type Transform. Is it there to replace the functionality of the [SerializeField] List Waypoints; in the enemyPathing? and if so, is it reading the waypoints directly from the pathing gameobject without the need for us to add each waypoint like we did in the enemy inspector?

Foreach loops are a little confusing at first. So basically what’s happening is you’re creating a new empty list. Then the foreach loop iterates over all the childed transforms in the pathPrefab provided. So for example if there was 3 children it would start with the first one and the reference to that child is the variable “child” defined in your loop when waveWayPoints.Add() is called it’s adding that child to the new list and it will keep doing that until it runs out of children. Then finally it returns the newly populated list.

I hope that makes sense and is helpful.

1 Like

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

Privacy & Terms