First, we call
FindObjectsOfType<Enemy>(); to get all active Enemy objects in our scene.
Then we create a variable named
closestTarget and set it to
null because we don’t know which Enemy object is the closest. Then we create another variable to increase the readability as the name
Mathf.Infinity is rather meaningless in the context of our method.
Now we iterate over our enemies in the
enemies array. We use a foreach-loop. We check the distance between our current game object and the current enemy in each iteration step. If the
targetDistance is lower than the
maxDistance. We assign our current enemy to
closestTarget. And we assign the distance between our enemy which appears to be the closest to
maxDistance because the closest enemy is either this enemy or one where the distance value is even lower.
After we checked all enemies, we assign the value of the
I hope this cleared it up for you. If not, I would recommend to rewatch the video at least one more time without following along. Maybe with another explanation in mind, the Gary’s explanation will make more sense.