- Home /
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 ?
Answer by Fattie · Feb 09, 2016 at 04:27 PM
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. Ins$$anonymous$$d, sort by squared distance (VectorA-VectorB).sqr$$anonymous$$agnitude. 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)
Your answer
Follow this Question
Related Questions
How to add and sort a list of gameobjects by tag? 2 Answers
Sorting list of Transforms 1 Answer
A node in a childnode? 1 Answer
Sorting a list of GameObjects by accessing their int values 2 Answers
Object Association in a List 1 Answer