Question about foreach

Hello.
I think im not sure if i understood this perfectly so here we go.

    private void SetLaneSpawner()
    {
        AttackerSpawner [] spawners  = FindObjectsOfType<AttackerSpawner>();

        foreach (AttackerSpawner spawner in spawners)
        {
            bool isCloseEnough = (spawner.transform.position.y - transform.position.y) <= Mathf.Epsilon;  //( Mathf.Abs(spawner.transform.position.y - transform.position.y) <= Mathf.Epsilon);
            if (isCloseEnough)
            {
                myLaneSpawner = spawner;
            }
        }
    }

1)So in this method we check for each spawner if its 0 or less.Then if its true then we assign the a new variable myLaneSpawner .
2) Now here comes what i dont understand.We call this SetLaneSpawner() method in Start.
In my logic this should run only on the begging then thats it.I mean the method does the calculation to bool isCloseEnough only a SINGLE TIME.Then how do we know if a new Lizard is spawning and whats his coordinate? I hope i could write normaly my question if not i try again ;).

Hi Shaktillar,

You are right. Since Start() gets called right after the object has been created, the spawner object (or nothing) gets assigned to myLaneSpawner “at the beginning”.

If everything goes right, our myLaneSpawner variable holds a reference to a Spawner game object in the scene. Our enemies get parented to a Spawner game object during runtime. If “our” referenced Spawner game object contains a child, we know that it must be an enemy because, otherwise, the childCount would be 0.

Did this clear it up for you?


See also:

:frowning: No
Ok let me ask then this way…the foreach loop keeps looping forever?Even if its in start?

The foreach loops keeps iterating over the elements in spawners as long as there are elements. Usually, the number is limited but if you added elements to the spawners arrays in each iteration step, the foreach loop would go on forever.

:wink: Yes this makes sense now.I was thinking it is iterating 1 time then bye bye.If it keeps iterating then it keeps updating the variable too.

Excatly. The first variable is the interation variable which holds the value of the current interation step.

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

Privacy & Terms