- Home /
Physics2D.Linecast and Physics2D.Raycast don't seem to return null
Physics2D.Linecast and Physics2D.Raycast don't seem to return a null RaycastHit2D as the help documentation would seem to suggest they should.
I keep getting null reference exceptions. Is there a bug with 3.4.x, I have checked and found no bug report.
I have the following code:
RaycastHit2D hit = Physics2D.Linecast(new Vector2(a.x, a.y), new Vector2(b.x, b.y));
if (hit == null)
return;//The Unity Editor says this is unreachable ;_;
print(hit.transform.name); //If there is a collider in the linecast, then this works
I get the same result with this:
RaycastHit2D hit = Physics2D.Linecast(new Vector2(a.x, a.y), new Vector2(b.x, b.y));
if (hit != null)
print(hit.transform.name); //If there is a collider in the linecast, then this works
Using Physics2D.Raycast gets me the same result
I've seen this since day 1 of the 2D stuff. The workaround:
if (hit != null && hit.transform != null)
or more typically:
if (hit != null && hit.collider != null)
Answer by DaemonBreed · May 07, 2014 at 08:38 PM
You need to compare the collider, the solution is as follows:
RaycastHit2D hit = Physics2D.Linecast(new Vector2(a.x, a.y), new Vector2(b.x, b.y));
if (hit.collider == null)
return;
@DaemonBreed - you need to be careful. I believe that sometimes the 'hit' is null.
I don't think so, according to the editor RaycastHit2D can never be null. Seems like a pretty stupid design decision to have RaycastHit2D and RaycastHit perform differently
You're right. It appears to be a struct. That explains some things. Thanks.
Your answer
![](https://koobas.hobune.stream/wayback/20220613144457im_/https://answers.unity.com/themes/thub/images/avi.jpg)