3
\$\begingroup\$

Let's say I have a Raycast, but I don't want it to collide with any triggers. I don't want to change the Project settings since that's a little inflexible.

How can I have a Raycast ignore any triggers?

\$\endgroup\$
7
\$\begingroup\$

There is a (optional) parameter for that in Physics.RayCast which is available in Unity 5.2 and up:

public bool RaycastNoTriggers(Vector3 startPosition , Vector3 direction, float distance)
{
    Ray ray = new Ray(startPosition, direction);
    RaycastHit hit; 
    return Physics.Raycast(ray, out hit, distance, DefaultRaycastLayers, QueryTriggerInteraction.Ignore);

}
\$\endgroup\$
1
  • \$\begingroup\$ Just a note as I ran into an issue with the 5.3.0f4 build of unity and Raycast's Ignoring triggers, you need to specify the distance. The Method without distance is currently bugged and does not ignore triggers. \$\endgroup\$ – Latency Dec 21 '15 at 15:21
0
\$\begingroup\$

Select a tag to all triggers called "Ignore Raycast" this will make the Ray ignore the triggers and pass through.

\$\endgroup\$
-1
\$\begingroup\$
public bool RaycastNoTriggers(Vector3 startPosition , Vector3 direction, float distance)
{
    Ray ray = new Ray(startPosition, direction);
    RaycastHit hit; 
    Physics.Raycast(ray, out hit, distance);
    if (hit.collider != null && !hit.collider.isTrigger) {
        return true; 
    }
    return false;

}
\$\endgroup\$
2
  • \$\begingroup\$ But what about geometry that is behind the trigger? \$\endgroup\$ – ratchet freak Oct 5 '15 at 8:28
  • 1
    \$\begingroup\$ This solution will cause triggers to "hide" any objects which are behind them. Are you sure that this is the solution you want? \$\endgroup\$ – Philipp Oct 5 '15 at 15:17

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.