- Home /
Sort - OrderBy GameObjects by Distance
Hi guys, i have a problem on my code. I have a list with the type of GameObject, at somewhere i add some GameObjects to the list. After all, i want to sort the list by distance to the this gameObject, and i test it with drawline but it doesn't work properly.
As you see, it's not the nearest OR farest object. So why is the reason of this, how can i do that? Thanks & have a nice day...
I think
list.OrderBy(x => Vector.Distance(this.transform.position, x.transform.position)).ToList();
Should work (asu$$anonymous$$g that the list is consisted of GameObject's). Anyways, you need to use property from the implicit parameter x in order to apply the ('foreach element effect').
Answer by esref_21 · Jul 20, 2016 at 08:54 PM
It didn't worked too, but i have found the solution. All of OrderBy codes doesn't work properly for some reason but with the Sort function, i have reached to succes. Solution is: Hedefler.Sort((v1, v2) => (v1.transform.position - transform.position).sqrMagnitude.CompareTo((v2.transform.position - transform.position).sqrMagnitude)); Thanks for the interest, have a nice day! :)
Answer by Dave-Carlile · Jul 20, 2016 at 12:03 PM
According to the documentation, OrderBy doesn't sort the list in place - it returns a result that will be sorted once you enumerate over it. So you need to assign the result of OrderBy to a list and then use that.