OverlapSphere doesn't detect rigidbodies

I’m trying to detect all the nearby rigidbodies with overlap sphere so I can apply an explosion force to them, but what I noticed was that my player wasn’t getting knocked back so I decided to start testing stuff and found that any object with a rigidbody doesn’t get detected, no matter what layer it’s on.

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Explosion : MonoBehaviour
{
    public float force, radius;
    
    private void Start()
    {
        Collider[] cols = Physics.OverlapSphere(transform.position, radius);

        foreach ( Collider col in cols )
        {
            Rigidbody rb = col.GetComponent<Rigidbody>();
            Debug.Log("col name: " + col.gameObject.name);
            if ( col.isTrigger || rb == null )
            {
                Debug.Log("No rb or col is trigger");
                return;
            }

            rb.AddExplosionForce(force, transform.position, radius);
        }
    }
}

What causes this?

You’re prematurely aborting the method at line 20. Just because one of the colliders doesn’t have a rigidbody doesn’t mean it should stop checking the rest of them.

Try this:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Explosion : MonoBehaviour
{
    public float force, radius;
    
    private void Start()
    {
        Collider[] cols = Physics.OverlapSphere(transform.position, radius);
        foreach ( Collider col in cols )
        {
            Rigidbody rb = col.GetComponent<Rigidbody>();
            if (rb)
            {
                rb.AddExplosionForce(force, transform.position, radius);
            } 
        }
    }
}
1 Like

As a side note to the above, if you want to skip an iteration you can use the continue; keyword.

So instead you’d use:

if ( col.isTrigger || rb == null )
{
    continue;
}
1 Like