- Home /
Raycast not working
I've got a scene with gameobjects with mesh colliders and layer set to a custom layer called "outer space". I try to shoot rays from the camera to these objects, so I have a script attached to the camera where I do:
if (Physics.Raycast(transform.position, transform.forward, hit))
//...
and that works, but when I do:
if (Physics.Raycast(transform.position, transform.forward, hit, Mathf.Infinity, LayerMask.NameToLayer("outer space")))
then I get no hit.
Any idea why it doesn't work ? (there are other objects in the scene with a different layer, which I do not want the raycast to hit)
Answer by rutter · Mar 16, 2012 at 07:40 PM
Instead of just:
LayerMask.NameToLayer("outer space")
Try this:
1 << LayerMask.NameToLayer("outer space")
Reason is, NameToLayer()
returns a layer index, but Raycast()
wants a layer mask. The two are not quite the same thing. To collide against layer 9, you want the 9th bit of your layer mask set, which we can get by bitwise shifting: 1 << 9
.
Thanks a lot, that totally fixed it. kinda weird though that they made it this way though
Answer by youblistermypaint · Sep 03, 2015 at 05:42 PM
For newer versions of Unity you can use LayerMask.GetMask("outer space")
instead of the bitshift method suggested by @rutter.
Your answer
Follow this Question
Related Questions
How to make my raycast also hit deactive objects WITHOUT showing the object? 1 Answer
Return Objects hit by raycast, check against a array of all objects? 1 Answer
unity raycast layers in Multiplayer 0 Answers
2D Raycast Layer Mask not working 1 Answer
Physics2D, weird layerMask behavior on Linecast, Raycast and OverlapPoint 2 Answers