How to find static objects in radius? Physics3D

I did a bunch of googling around for a solution to this but I just can’t seem to get it working.


I have a bunch of static 3D objects with CapsuleColliders on the same layer and I want to be able to iterate through ones of the same kind within radius of the player so I can mess with their variables. Assume I have hundreds of objects of 2 kinds; RED and BLUE and I want to grab all the BLUE objects, ignoring RED within the sphere radius of PLAYER.


Here’s the script I’m working with (I’ve shortened it for readability):

float radius = 50f;

// the trigger for this is a skill use / keybind
private void GetObjectsInRadius()
{
     int layerMask = LayerMask.GetMask(BLUE.gameObject.layer);
     Vector3 pos = PLAYER.gameObject.transform.position;

     Collider[] colliders = Physics.OverlapSphere(pos, radius, layerMask);

     foreach (Collider collider in colliders)
     {
     // if object BLUE, do stuff
     }
}

Note that this is a prototype script because I’m working on setting up basic game functionality. The objects are static, using a CapsuleCollider with no rigidbody.


In theory the OverlapSphere() should be able to collide with both RED & BLUE objects but for whatever reason, it is only detecting RED. I know this because I was logging objects in the foreach loop and it only logged RED. I also logged their world position to make sure that the Sphere is appearing at the correct position and has BLUE objects within range. It only detects RED, I don’t know why.


I saw a video of someone using OverlapCircleAll() for 2D colliders and mentioning that OverlapCircle() only collides with one object. OverlapSphere() however doesn’t have an OverlapSphereAll() method, so I’m wondering if it’s functioning the same way as OverlapCircle() and I have to use something else? I also read from someone saying that OverlapSphere() only detects objects on the edge of the sphere. I can’t confirm whether that’s true or not but the documentation states that it detects everything within the sphere.


I want to be able to do this at runtime without iterating through all loaded game objects. I think using Physics with colliders is probably the best way and shouldn’t be too bad on performance since I’m only grabbing a handful of objects.

The problem is in the way you’re using LayerMask.GetMask. You must specify the layer names you want to construct the mask with. For example, if your red layer is named “Red Objects” and the blue layer “Blue Objects” then the correct way would be:

int layerMask = LayerMask.GetMask("Red Objects", "Blue Objects");