# Sort a list of objects by distance?

Today I got issue with a script we solved here. OK, Here if enemy enter player ring, he "enemy" gets inside player list. Now, if group of enemies get inside this the ring I need to sort them by distance from player. The first one in the list will be the closest enemy from player, and so on. If one die, new enemy will add to list that nearest/closest to player. Will my GameObject list allow me to do this ? or I need to make new Vector3 list ? I'm using System.Linq.

    public List<GameObject> enemiesInRange = new List<GameObject>();
public int hox;

// Update is called once per frame
void Update()
{

hox = enemiesInRange.Count;
if (hox == 3)
print("Frist enemy near you is " + enemiesInRange[0] + ", " + enemiesInRange[1] + ", " + enemiesInRange[2]);
//   enemiesInRange[0].GetComponent<enemypath>().enemey_checker = true;
//   enemiesInRange[1].GetComponent<enemypath>().enemey_checker = true;
//   enemiesInRange[2].GetComponent<enemypath>().enemey_checker = true;

}

void OnTriggerEnter(Collider other)
{
if (other.CompareTag("enemy") && hox < 3)
}

void OnTriggerExit(Collider other)
{
if (other.CompareTag("enemy"))
enemiesInRange.Remove(other.attachedRigidbody.gameObject);
}


I really hope to solve this issue and finish from this point.

When in doubt, I recommend consulting the documentation for the types you're using. Even using Intellisense to browse the members of List<T> would let you discover List.Sort.

This lets you sort a list using any Comparison method you choose, like for instance this one:

int SortByDistanceToMe(GameObject a, GameObject b) {
float squaredRangeA = (a.transform.position - transform.position).sqrMagnitude;
float squaredRangeB = (b.transform.position - transform.position).sqrMagnitude;
return squaredRangeA.CompareTo(squaredRangeB);
}


Then you can simply call:

enemiesInRange.Sort(SortByDistanceToMe);


This is a quick & dirty solution that does strictly more vector calculations than necessary, but for a handful of enemies that won't be a problem. If you want to run this on hundreds of enemies then you'll want to pre-compute your distances first, then find the ranked/sorted order of that collection.

• By the way: The Reason why DMGregory is using sqrMagnitude here instead of magnitude is because the square of the magnitude of a vector is faster to compute than the actual magnitude. If you only care about which one is closer, then comparing the squares of the distances instead of the actual distances does the job just as well and saves you some CPU cycles. – Philipp Jan 5 at 17:34
• Thank you guys for all what you do here. I spend my day reading about the OrderBy & ToList, reading some saying crazy things, or make new vector3 and merge both lists...headache. Really good to have people here give you the solution and explain why he did this and where is your mistake to learn. – Omer Jan 5 at 17:48