InvalidOperationException: 如果碰撞器未设置为,Physics.Raycast 查询可能会多次命中同一碰撞器
InvalidOperationException: Physics.Raycast query may hit the same collider multiple times if the collider is not set to
ID: unity/raycast-multiple-collider
版本兼容性
| 版本 | 状态 | 引入 | 弃用 | 备注 |
|---|---|---|---|---|
| Unity 2022.3 | active | — | — | — |
| Unity 2023.1 | active | — | — | — |
| Unity 2023.2 | active | — | — | — |
根因分析
当碰撞器有多个接触点或未配置 'QueryTriggerInteraction.Ignore' 或正确的层过滤时,RaycastNonAlloc 查询会为单个碰撞器返回重复命中。
English
A RaycastNonAlloc query returns duplicate hits for a single collider when the collider has multiple contact points or is not configured with 'QueryTriggerInteraction.Ignore' or proper layer filtering.
官方文档
https://docs.unity3d.com/ScriptReference/Physics.RaycastNonAlloc.html解决方案
-
Use 'HashSet<Collider>' to deduplicate hits after calling RaycastNonAlloc. Example: HashSet<Collider> hitColliders = new HashSet<Collider>(); foreach (var hit in results) hitColliders.Add(hit.collider);
-
Set 'QueryTriggerInteraction.Ignore' in the raycast call and use layer masks to exclude duplicate-prone colliders. Example: Physics.RaycastNonAlloc(ray, results, maxDistance, layerMask, QueryTriggerInteraction.Ignore);
无效尝试
常见但无效的做法:
-
60% 失败
Triggers can still cause duplicate entries in non-alloc queries; the issue is about query filtering, not trigger state.
-
80% 失败
RaycastAll also returns duplicates; the problem is generic to all raycast methods when colliders have multiple shapes.
-
70% 失败
Contact offset affects collision detection resolution, not raycast query deduplication.