Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a specific order to the Colliders that Physics.OverlapSphere() returns?

Is there a specific order to the Colliders that Physics.OverlapSphere() returns? (e.g. by proximity)

Unity Docs give no indication -

Returns an array with all colliders touching or inside the sphere.

I also found this Unity forum topic, which states that there is no specific order, but the topic is from 2012 and doesn't seem to have had much attention so I wanted to check here.

like image 812
dferdo61 Avatar asked Dec 09 '25 01:12

dferdo61


1 Answers

Afaik you can't rely on the order of physics in general. The order might depend on the order in the hierachy, not sure. But I'm quite sure it does not depend on proximity.

Something you could simply test ofcourse ;)


You could however simply sort them by proximity just to be sure using Linq OrderBy

using System.Linq;

...

var colliders = Physics.OverlapSphere(center, radius);
var orderedByProximity = colliders.OrderBy(c => (center - c.transform.position).sqrMagnitude).ToArray();

This sorts them at least roughly by ascending distance to their according GameObjects positions, which is perfectly fine if all the objects have the same size.

If you want the actual distance you would have to get creative and e.g. take their bounds into account.

like image 126
derHugo Avatar answered Dec 10 '25 13:12

derHugo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!