Unable to understand this lecture (124 - Target Closest Enemy)

Can Somone please explain the logic behind this code,what exactly is code doing ?

  void FindClosestTarget()
        Enemy[] enemies = FindObjectsOfType<Enemy>();
        Transform closestTarget = null;
        float maxDistance = Mathf.Infinity;

        foreach(Enemy enemy in enemies)
            float targetDistance = Vector3.Distance(transform.position, enemy.transform.position);
            if (targetDistance < maxDistance)
                closestTarget = enemy.transform;
                maxDistance = targetDistance;
        Target = closestTarget;  

Hi Blaze,

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 closestTarget to Target.

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. :slight_smile:

See also: