How can I do a 2D raycast against one specific collider?

For 3D colliders ( Collider ), I can do:

collider.Raycast(ray, out hit, rayLength)

But for 2D colliders ( Collider2D ), there is no Raycast method.

There’s this angry feature request from more than a year ago, but no response.

I cannot use layer masks, because I cannot predict on which layer my collider will be.

(How) can I do it?

Not sure if you want your rays to be exclusively on a 2D surface, If so, perhaps using the Physics2D raycast functions will work for your situation?

If you want to detect an intersection with a FACE, rather than a EDGE, then the Physics (3D) raycast, should work.

Hope it will help others, I needed to check for intersection in the same scenario, I used this:

collider.bounds.IntersectRay()

I was trying to solve a similar problem on my project and ended up with this workaround solution. I’m not sure if it’s the best, but it seems to get the job done.

The key here is that one of the overload methods for Physics2D.Raycast lets you output an array or list of results instead of just getting the first hit. Then you can check through your results list and find the one that matches the game object you’re checking against.

         List<RaycastHit2D> resultsList = new List<RaycastHit2D>();

         Physics2D.Raycast(raycastStart, raycastDirection, contactFilter, resultsList, rayCheckDist);

         foreach (RaycastHit2D result in resultsList)
         {
            Debug.Log(result.collider.gameObject);
            if (result.collider.gameObject == gameObjectToCheckFor)
               {whatever you want to happen here}
         }