unity
runtime_error
ai_generated
true
NullReferenceException:Physics.OverlapSphereNonAlloc 返回了空的结果数组
NullReferenceException: Physics.OverlapSphereNonAlloc returned null results array
ID: unity/physics-overlap-sphere-null
95%修复率
88%置信度
1证据数
2023-09-18首次发现
版本兼容性
| 版本 | 状态 | 引入 | 弃用 | 备注 |
|---|---|---|---|---|
| 2020.3.48f1 | active | — | — | — |
| 2021.3.30f1 | active | — | — | — |
| 2022.3.10f1 | active | — | — | — |
根因分析
传递给 OverlapSphereNonAlloc 的结果数组在调用方法之前为 null 或未初始化。
English
The results array passed to OverlapSphereNonAlloc is null or not initialized before calling the method.
官方文档
https://docs.unity3d.com/ScriptReference/Physics.OverlapSphereNonAlloc.html解决方案
-
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);`
无效尝试
常见但无效的做法:
-
95% 失败
The null check doesn't prevent the NullReferenceException from being thrown when accessing the uninitialized array in the method call itself.
-
99% 失败
The error is about the array being null, not its size; size is irrelevant if the array reference is null.
-
30% 失败
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.