Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- List<Enemy> enemies; //needs to be populated somehow.
- int closestEnemy = 0; //the index of the closest enemy
- float closestEnemyDistance = float.MaxValue; //the distance of the closest enemy, used in the check below
- for(int i = 0; i < enemies.Count; i++){
- float dist = Vector3.Distance(player.transform.position, enemies[i].transform.position); //get the distance between the player and the enemy at enemies[i];
- if(dist < closestEnemyDistance){ //if this distance is smaller than whatever we have saved as the closest distance, it means this enemy is closer to the player than the enemy we previously thought was the closest.
- closestEnemyDistance = dist; //set this distance of the closer enemy to the 'closest so far'
- closestEnemy = i; //save it's index
- }
- }
- //when the loop is all done, the enemy (index) with the closest distance to the player will be saved in 'closestEnemy'
- //the closest enemy is
- Debug.Log(enemies[closestEnemy]);
Advertisement
Add Comment
Please, Sign In to add comment