sort a List of GameObjects by distance?

i have a List m_list

its full of gameobjects

i have my player position
and i want to order the m_list by the distance from my player.
how do i go about this ?

1 Answer

1

If using System.Linq;

hits = hits.OrderBy(
   x => Vector2.Distance(this.transform.position,x.transform.position)
  ).ToList();

Linqless

hits.Sort(delegate(Enemy a, Enemy b)
 {return Vector2.Distance(this.transform.position,a.transform.position)
  .CompareTo(
    Vector2.Distance(this.transform.position,b.transform.position) );
});

Hope it saves some typing.

Great answer, worked like a charm. I think just to clarify for other beginners like myself the above solution is taking an array and comparing the distance to a point with each object in the array.

Don't sort by distance, it includes calculating a square root which is expensive. Instead, sort by squared distance (VectorA-VectorB).sqrMagnitude. It is much faster to compute (much much faster) and the result is mathematically proven to be the same (since sqrt is a rising one-to-one function for positive numbers, which a distance always is)