OverlapSphere finds all the overlapping colliders, creates a new array, puts the colliders inside of it, and returns that array.
For OverlapSphereNonAlloc, you send in an array, it finds all the overlapping colliders, puts them in the array, and returns how many colliders it found.
So for OverlapSphereNonAlloc, you can re-use the same array for subsequent calls to the same method. OverlapSphere generates a new array each time.
OverlapSphereNonAlloc is generally a better solution, since it doesn’t generate new arrays that slowly fills the memory (causing GC spikes when you run out). There’s some downsides, though:
- The remaining spaces in the array is not changed, so you have to be careful to only read up to the returned number from the array.
- If you send in a too small array, you’ll miss data. The order of the returned colliders are not documented, and I doubt it’s consistent, so you might lose the most important results.
OverlapSphereNonAlloc example:
private Collider[] overlapResults = new Collider[10];
private void Update() {
int numFound = Physics.OverlapSphereNonAlloc(transform.position, 10f, overlapResults);
for (int i = 0; i < numFound; i++) {
Debug.DrawLine(transform.position, overlapResults[i].transform.position, Color.red);
}
}