- Home /
Layer mask doesn't work...
Hello i'm using a layer mask while ray casting but whatever i do it doesn't ignore the given layer. I used this method before & was working fine. Guess there is a problem that a i cannot resolve. Here is how i use the method:
// Ignore layers 21 & 0
int layerMask = ~LayerMask.GetMask(LayerMask.LayerToName(21), LayerMask.LayerToName(0));
if (Physics.Raycast(position, direction, out hit, maxDistance, layerMask)) {
// Always reaching this point where hit.transform.gameObject.layer = 21
if (XLayers.shouldDoStuff(hit.transform.gameObject.layer)) {
// DO stuff
} else{ // other stuff }
} else { some other stuff }
As far as i know this symbol ( ~ ) makes it ignore the given layers. I tried to remove it too the result is the same. Also i tried to send 0 as the layer mask which means ignore all layers, i this case the ray collides with nothing as expected . Any advice appreciated thanks.
Try :
int layer$$anonymous$$ask = ( 1 << 0 ) | ( 1 << 21 );
layer$$anonymous$$ask = ~layer$$anonymous$$ask;
Thx for suggestion but the result is the same. Hit layer is 21 :D
Answer by cosmos · Aug 09, 2019 at 12:40 PM
Got it. This is my prefab:
ParentGameObject ( Layer : 21, has rigidBody, has collider )
ChildGameObject ( Layer : 18, no ridigBody, has collider )
The parent layer is ignored as it should be & the child is collided with the ray.
BUT hit.transform.gameObject.layer returns you the layer of the gameObject that CONTAINS THE RIGIDBODY. Which is the ParentGameObject. Doesn't matter what layer is the game object contaning the collider.
For the solution I added a rigidbody to the ChildGameObject it works now.
Uhm, that's why the RaycastHit structure actually has a collider field as well which contains a reference to the collider that was hit.