You can use Linq OrderBy
like
using System.Linq;
...
// Wherever you get this from
List<EachEnemy> allEnemies;
// Sorted by the distance to this object
var sortedEnemies = allEnemies.OrderBy(enemy => (transform.position - enemy.coords).sqrMagnitude);
// Or depending on how your class is used simply
//var sortedEnemies = allEnemies.OrderBy(enemy => enemy.distance);
// This would return null if the list was empty
// Or the first element of the sorted lost -> smallest distance
var nearestEnemy = sortedEnemies.FirstOrDefault();
Note that using
OrderBy(enemy => (transform.position - enemy.coords).sqrMagnitude);
Would be more efficient than actual calculating the distances first since it skips using a square root on all the vector sqrMagnitude
s. Since a > b
also implies a² > b²
and we know that a magnitude is always positive it is enough to know the sqrMagnitude
s of all the delta vectors in order to sort them.
The advantage of this would be that you can also get the second and third closest enemies etc.