OverlapSphereNonAlloc Not Working?

Ok, so I’m trying to write a simple little script to detect objects that can be picked up in front of my character. If I use Physics.OverlapSphere I get the results I want, but if I use the exact same values in Physics.OverlapSphereNonAlloc then I don’t detect any collisions. It’s running every frame, so I’d prefer to use the less-garbage-y approach.

Here’s my code:

[SerializeField]
private float pickupSphereForward = 0.5f;

[SerializeField]
private float pickupSphereSize = 1f;

private Collider[] nearbyPickupables;

private void Update()
{
        // This works.
        nearbyPickupables = Physics.OverlapSphere(transform.position + transform.forward * pickupSphereForward,
                                                        pickupSphereSize,
                                                        LayerManager.PickupableMask);

        if (nearbyPickupables.Length > 0)
        {
            Debug.Log("Nearby pickupables!");
        }

        // This doesn't work.
        if (Physics.OverlapSphereNonAlloc(transform.position + transform.forward * pickupSphereForward,
                                              pickupSphereSize,
                                              nearbyPickupables,
                                              LayerManager.PickupableMask) > 0)
        {
            Debug.Log("Nearby pickupables!");
        }
}

At this point in time I really just need to figure out what’s going wrong on point of principle. I’m not going to sleep properly otherwise haha

This was caught me out too yesterday.

The Collider nearbyPickupables needs to be initialized to a useful size. So something like:

Collider nearbyPickupables = new Collider[10];

The function lets you allocate space for collision data once and then re-use it to prevent allocations each time it’s called. Initializing the array is how you do that one-time allocation of space. Without that, the maximum number of colliders that can be returned by the function is zero.

The array can be smaller than the number of colliders that might actually occur in some position. That won’t generate an error. Any extra colliders will just be ignored.

1 Like