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\$

3 Answers 3

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, 2015 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\$ Oct 5, 2015 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, 2015 at 15:17

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .