- Home /
Why isn't my RaycastHit2D working?
This is my first time using RaycastHit2D, but I really can not seem to get it working and the documentation doesn't help either.
void FixedUpdate () {
RaycastHit2D hit = Physics2D.Raycast(transform.position, Vector2.down, 100f, LayerMask.NameToLayer("Ground"));
Debug.DrawRay(transform.position, Vector2.down * 100f, Color.red);
if (hit.collider != null) {
Debug.Log(hit.point);
Debug.DrawLine(transform.position, hit.point, Color.red);
}
}
It doesn't seem to be hitting anything at all, even though I an absolutely certain that it should be hitting an object in the Ground layer.
Could anyone please help me out?
Where are you casting from? If you're on the ground when you do the raycast, it might be going through. You could try casting from a slightly raised point.
Also, does it work when you remove the layer parameter? Just so we can eli$$anonymous$$ate that possibility.
Answer by Bunny83 · Apr 30, 2018 at 02:18 AM
LayerMask.NameToLayer gives you the layer index and not a layer mask. You either want to use LayerMask.GetMask("Ground") instead or just use 1 << LayerMask.NameToLayer("Ground")
as layer mask.
Though an usually easier approach would be to declare a public LayerMask variable on your script and set the layers you want in the inspector. In your actual raycast you can just use yourLayerMask.value then.
Thank you so much! I didn't know that there is a difference between a layer index and a layer mask. The public Layer$$anonymous$$ask variable is a really helpful suggestion as well.
Your answer
![](https://koobas.hobune.stream/wayback/20220612161736im_/https://answers.unity.com/themes/thub/images/avi.jpg)