Search Unity

Question How do I make a raycast ignore regular colliders, but still collide with trigger colliders?

Discussion in 'Physics' started by AveyHun, Jul 23, 2021.

  1. AveyHun

    AveyHun

    Joined:
    Jul 23, 2021
    Posts:
    2
    I'm pretty new to unity, so I basically have no clue what I'm doing.

    I've tried to search for a solution, and I couldn't find anything. I've also searched through the Unity Documentation and haven't found anything either. Although, I could just be bad at looking things up.

    I know that I can add
    QueryTriggerInteraction.Collide
    to make the query include triggers, but the issue i'm having is excluding non-trigger colliders.
     
  2. RadRedPanda

    RadRedPanda

    Joined:
    May 9, 2018
    Posts:
    1,648
    Is there something wrong with just using the Layer system? If not, you can just set the Layer of any object you want the Raycast to actually hit, and set the Raycast LayerMask parameter to only hit that Layer.
     
  3. lightbug14

    lightbug14

    Joined:
    Feb 3, 2018
    Posts:
    447
    Use the "All" version of a physics query (raycast, spherecast, etc) of even better the NonAlloc version. For the NonAlloc version you need to pass an array of RaycastHit to the function. After that, you need to loop over the array and get the RaycastHit that you are interested in.

    Code (CSharp):
    1. RaycastHit[] buffer = new RaycastHit[20] // 20 hits max
    2.  
    3. ...
    4. int hits = Physics.RaycastNonAlloc( ... , buffer , ... ,QueryTriggerInteraction.Collide );
    5.  
    6. RaycastHit closestHit = new RaycastHit();
    7. closestHit.distance = Mathf.Infinity;
    8. for( int i = 0 ; i < hits ; i++ )
    9. {
    10.        RaycastHit raycastHit = buffer[i];
    11.  
    12.       // If is not a trigger then ignore it
    13.        if( !raycastHit.collider.isTrigger )
    14.             continue;
    15.  
    16.        // Get the closest hit available
    17.        if( raycastHit.distance < closestHit.distance )
    18.             closestHit = raycastHit;
    19. }
    20.  
    21. // Do whatever you want with the trigger..
    22.  
    23.  
    24.  
    [Sorry if there are errors]