Check what collider was hit by raycast

I have an object with 2 colliders:Sphere and box.
The sphere collider is inside box collider.
I tried this:

if (Physics.Raycast(ray, out hit, 100.0f))
{
   if (hit.collider is SphereCollider)
   {
        
   }
}

It isn’t working. I know that here is the problem because this is working:

if (Physics.Raycast(ray, out hit, 100.0f))
{
   if (hit.collider is BoxCollider)
   {
       
   }
}

The sphere collider isn’t detected!

Use Debug.Log() to print out what the hit.collider is.

Okay, I just re-read this… if the sphere is inside the box, it’s always going to hit the box.

Some Options:

You can use Layers to mask out what you’re interested in, but then the colliders have to be on separate GameObjects, since layers are set at the GameObject level, not the Component (Collider) level.

You can use RaycastAll() and see all the things hit by your raycast and look through them:

https://docs.unity3d.com/ScriptReference/Physics.RaycastAll.html