unity runtime_error ai_generated true

InvalidOperationException: Physics.Raycast query may hit the same collider multiple times if the collider is not set to

ID: unity/raycast-multiple-collider

Also available as: JSON · Markdown · 中文
90%Fix Rate
87%Confidence
1Evidence
2024-01-10First Seen

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
Unity 2022.3 active
Unity 2023.1 active
Unity 2023.2 active

Root Cause

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.

generic

中文

当碰撞器有多个接触点或未配置 'QueryTriggerInteraction.Ignore' 或正确的层过滤时,RaycastNonAlloc 查询会为单个碰撞器返回重复命中。

Official Documentation

https://docs.unity3d.com/ScriptReference/Physics.RaycastNonAlloc.html

Workarounds

  1. 95% success 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);
    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);
  2. 85% success 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);
    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);

中文步骤

  1. 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);
  2. 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);

Dead Ends

Common approaches that don't work:

  1. 60% fail

    Triggers can still cause duplicate entries in non-alloc queries; the issue is about query filtering, not trigger state.

  2. 80% fail

    RaycastAll also returns duplicates; the problem is generic to all raycast methods when colliders have multiple shapes.

  3. 70% fail

    Contact offset affects collision detection resolution, not raycast query deduplication.