问题
I have some GameObject in an array and I'd like to sort them by distance based on a point in space. So basically I'm searching for an point sorting by distance algorithm.
I'm sure this is basic sorting algorithm stuff but I couldn't find a valid answer on Google so far.
Thanks for the help !
回答1:
This should get you started:
System.Array.Sort<GameObject>(arrayOfGameObjects,
(g1, g2) =>
(Vector3.Distance(target,g1.transform.position) <
Vector3.Distance(target,g2.transform.position))?-1:1);
回答2:
Jerdak answer is right.
If you can use an ordered copy of the array, instead of ordering the original one, an alternative is to use Linq
OrderBy extension method to Enumerable
:
Vector3 targetPos;
IEnumerable<Pet> ordered = arrayOfGameObjects.OrderBy(
obj => Vector3.Distance(obj.transform.position,targetPos));
来源:https://stackoverflow.com/questions/15148874/sort-gameobjects-from-an-array-to-a-reference-point-in-space