LayerMask not working

The RayCast documentation says:

You may optionally provide a LayerMask, to filter out any Colliders you aren’t interested in generating collisions with.

but… I have this piece of code:

      LayerMask mask = LayerMask.GetMask("Ground");
      if(Physics.Raycast(ray,out hit,mask)) {
         if(hit.collider.CompareTag("Ground")) {
            return hit.point;
         }
         Debug.Log("not ground: "+LayerMask.LayerToName(hit.collider.gameObject.layer));
      }

which produces this output:

7178476--860581--layermask.png

Unless I’m misunderstanding something, any colliders outside the Ground layer have to be excluded, and because of that, the only possible way to reach the Debug statement is when the collider is not tagged as “Ground” but still on the Ground layer. However, the log shows that colliders from other layers are also being hit.

So the question is: is this a bug, or there’s something I’m not seeing?

My fault… for anyone having a similar problem, if you’re using Visual Studio, do not, and I repeat, do not, trust blindly what intellisense tells you. When typing the raycast statement it showed me the next parameter was the layermask and I assumed that was correct, but no, it is the maximum distance.

22 Likes

I have never seen it give you the wrong arguments so any chance you can post a screenshot of this so we can see it. Should be simple if it’s doing it.

Note that there are multiple overloads so maybe that confused you: Physics.Raycast.

7179487--860770--intellisense.png

It was my fault because I assumed IntelliSense was pointing to the right overload, and I didn’t read the whole implementation, so when I saw “layerMask” I just went ahead and typed the corresponding parameter.

11 Likes

Yeah, layer-mask not being a special type but rather an int is kind of a pain in this circrumstance as it naturually gets consumed by float args like distance. ;(

4 Likes

THANK YOU so much ! This is the correct answer, keep an eye on the constructors of the Unity scripting API : https://docs.unity3d.com/ScriptReference/Physics.Raycast.html

3 Likes

This is still saving people from insanity, thanks dude!

2 Likes

Amazing, also was going nuts with this, then i read this, fixed the parameters and voala, everything working as expected.

1 Like

Thank you!!!

Thx I was having the same problem

1 Like