Sort GameObjects from an array to a reference point in space

夙愿已清 提交于 2021-01-28 05:35:12

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!