DMeville

Untitled

Mar 2nd, 2019
155
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 0.94 KB | None | 0 0
  1. List<Enemy> enemies; //needs to be populated somehow.
  2.  
  3. int closestEnemy = 0; //the index of the closest enemy
  4. float closestEnemyDistance = float.MaxValue; //the distance of the closest enemy, used in the check below
  5.  
  6. for(int i = 0; i < enemies.Count; i++){
  7.     float dist = Vector3.Distance(player.transform.position, enemies[i].transform.position); //get the distance between the player and the enemy at enemies[i];
  8.     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.
  9.         closestEnemyDistance = dist; //set this distance of the closer enemy to the 'closest so far'
  10.         closestEnemy = i; //save it's index
  11.     }
  12. }
  13. //when the loop is all done, the enemy (index) with the closest distance to the player will be saved in 'closestEnemy'
  14.  
  15. //the closest enemy is
  16. Debug.Log(enemies[closestEnemy]);
Advertisement
Add Comment
Please, Sign In to add comment