Raycast(2d) returns empty RaycastHit2d instead of null

I’m doing a ray cast on a specific layer. When I do so the Physics2D.Raycast returns an empty RaycastHit2D object, within which, all the class variables are empty non-null values. The result is I can’t tell if my ray cast has hit anything or not.


RaycastHit2D hit2d = Physics2D.Raycast(transform.position, direction,1, LayerMask.NameToLayer("Enemy"));
if (hit2d != null)
   // Do stuff

My “Do stuff” bit runs and throws an exception because hit2d.transform and .collider are empty but not null. AFAIK this is not the documented behaviour of Physics2d.Raycast.
How do I use this / use a work around?

edit: Oh and transform.position and direction both have magnitude > 0.

The example code in the reference is wrong. It turns out that a RaycastHit is a scruct (value type). You cannot even assign null to it. For example this will generate a compiler error:

 var hit : RaycastHit2D = null;

So you can check the collider or the transform:

if (hit2d.collider != null)
    // do stuff

The RaycastHit2D’s collider documentation says you can check the result directly (which uses the “implicit conversion operator converting to bool”):

RaycastHit2D result = Physics2D.Linecast(start, end, seeTargetMask);
if (result)
    // Find something we can hurt.

I think that’s clearer than checking the collider.

FYI, if you use a LayerMask member variable on your script (my seeTargetMask), you can set it through the GUI and don’t have to worry about shifting bits. That makes it harder to get wrong.