Physics.OverlapSphereNonAlloc bug?

Hello, I think I have found a bug in unity’s Physics.OverlapSphereNonAlloc. OverlapSphere (with alloc) returns hits, yet the non alloc version with the same input returns no hits

  private Collider[] hits = new Collider[20];

   ...

  position = Vector3.zero;
  range = 5f;

  Collider[] newhits = new Collider[20];
  newhits = Physics.OverlapSphere(position, range);

  int count = Physics.OverlapSphereNonAlloc(position, range, hits);

  Debug.Log("new hits length: " + newhits.Length);   // outputs 5
  Debug.Log("hits length: " + count);                           // outputs 0

Shouldn’t these return the exact same values? How can it be that these return different counts? I’m running this within the Update() function if that makes any difference.

I’m on 2022.3.40f1

Sure looks like it should, and it does for me.

Are you sure you don’t have a local variable called hits that is hiding the class instance??

Are the objects you are detecting right at the ragged edge of detection? I remember there were some blind spots in the capsule cast… (EDIT: or it might have been raycasting against a capsule collider, I forget, but there were edge case blind spots… but that seems an unlikely explanation with a sphere…)

ANOTHER EDIT… print the .Length of the hits array before using it… I bet it is either serialized as an empty array or null, perhaps because you have domain reload off.

1 Like

Also FWIW, this allocates two arrays unnecessarily:

You don’t need to allocate the array before hand:

Collider[] newhits = Physics.OverlapSphere(position, range);
1 Like

yeah I was shorthanding, here’s the full code of this class (adjusted to use the less efficient OverlapSphere instead of the NonAlloc) version:

 private Collider[] hits;

  public Constructor() {
     ...
     hits = new Collider[20];
  }

  public void CheckForHits(Vector3 position, float radius, LayerMask layerMask) {

 Collider[] newhits = Physics.OverlapSphere(position, range, layerMask, QueryTriggerInteraction.Ignore);

    int count = Physics.OverlapSphereNonAlloc(position, range, hits);

   Debug.Log("new hits length: " + newhits.Length);  // outputs 5
   Debug.Log("hits length: " + count);               // ouputs 0


   Debug.Log("hits" + count);
   Debug.Log("pos : " + position);
   Debug.Log("range: " + range);
   Debug.Log("lm " + layerMask.ToString());

   //for (int i = 0; i < count; i++) {
   foreach (Collider c in newhits) {
   ...

even using the layermask only in the non-alloc version I get the same output.

Ok so this must have been user error in some way. its working now. I’m not sure what has changed tbh, I must not have been initializing the hits array as I had thought I was. It would be nice if these physics methods would throw some kind of error if the hits array is null or size 0.