unity
runtime_error
ai_generated
true
NullReferenceException: Physics.OverlapSphereNonAlloc returned null results array
ID: unity/physics-overlap-sphere-null
95%Fix Rate
88%Confidence
1Evidence
2023-09-18First Seen
Version Compatibility
| Version | Status | Introduced | Deprecated | Notes |
|---|---|---|---|---|
| 2020.3.48f1 | active | — | — | — |
| 2021.3.30f1 | active | — | — | — |
| 2022.3.10f1 | active | — | — | — |
Root Cause
The results array passed to OverlapSphereNonAlloc is null or not initialized before calling the method.
generic中文
传递给 OverlapSphereNonAlloc 的结果数组在调用方法之前为 null 或未初始化。
Official Documentation
https://docs.unity3d.com/ScriptReference/Physics.OverlapSphereNonAlloc.htmlWorkarounds
-
98% success Initialize the results array before the call: `Collider[] results = new Collider[10]; int count = Physics.OverlapSphereNonAlloc(center, radius, results);`
Initialize the results array before the call: `Collider[] results = new Collider[10]; int count = Physics.OverlapSphereNonAlloc(center, radius, results);`
-
95% success Check if results is null before passing: `if (results == null) results = new Collider[10]; int count = Physics.OverlapSphereNonAlloc(center, radius, results);`
Check if results is null before passing: `if (results == null) results = new Collider[10]; int count = Physics.OverlapSphereNonAlloc(center, radius, results);`
中文步骤
Initialize the results array before the call: `Collider[] results = new Collider[10]; int count = Physics.OverlapSphereNonAlloc(center, radius, results);`
Check if results is null before passing: `if (results == null) results = new Collider[10]; int count = Physics.OverlapSphereNonAlloc(center, radius, results);`
Dead Ends
Common approaches that don't work:
-
95% fail
The null check doesn't prevent the NullReferenceException from being thrown when accessing the uninitialized array in the method call itself.
-
99% fail
The error is about the array being null, not its size; size is irrelevant if the array reference is null.
-
30% fail
OverlapSphere allocates a new array each call, which may fix the immediate null issue but introduces GC pressure and doesn't solve the root cause of uninitialized array.