OverlapSphere or Vec3.Distance

I need to do a radius check against ~100 rigidbody objects every frame.

Which one works faster? Physics.OverlapSphere or Vector3.Distance in a for loop?

Overlapsphere will return an array with all the colliders inside it. Since Unity probably uses a tree or another data structure to check rendering, collision, etc., it should be more optimized, but the only way to be sure is testing both methods.

One note: for the same result as Vector3.Distance but with better performance, instead of:

if (Vector3.Distance(pos1, pos2) < x)

use

if ((pos1 - pos2).sqrMagnitude < x*x)

(Sphere colliders most certainly use this for speed purposes)
Because .sqrMagnitude bypasses the square root part of finding the distance - by far the slowest piece of that function - it’s considerably faster to check distance this way.

hmm good tip…

on a very similar problem, if these 100 rigid bodies were all on a sphere, and could only move around the surface of the sphere, is there an even quicker way to check distances?

assuming the sphere center is at (0,0,0) and all objects are at a constant distance of r.

eg) you could use the dot product of 2 objects, the closer the scalar is to -1 the closer those objects actually must be, I just don’t know how to turn that back into gameunit distances… or whether that would be faster than the sqrmag method?

I did a check of 400 entities with sphere colliders using Physics2D.OverlapCircleNonAlloc vs checking distance using sqrMagnitude:
Physics took 0.06ms
Distance took 0.76ms

I’m sure this is all to do with the physics spatial partitioning, you could roll your own or use something like this GitHub - deadlyfingers/RTree: C# RTree compatible with Unity., and maybe the distance check would be faster then but for now 0.06 is pretty good.