Working with Layers question.

Not sure if this is a bug or I am missing something very obvious lol.

I have his line of code:

 if (Physics.Raycast(_weaponSelected.spawnPoint.transform.position,  _weaponSelected.spawnPoint.TransformDirection(Vector3.forward), out hit, 10f))
     
if (hit.transform.gameObject.layer == attacklayer) {

For some reason the last line of code never recognizes what is set in the attacklayer. Which I have set to “Enemy” in the inspector. I even debug.log the layer being hit by the Raycast and it comes up as layer 9 which is indeed the enemy layer. don’t get any errors or warnings.

but now if I use

 if (hit.transform.gameObject.layer != LayerMask.NameToLayer("Enemy"))

It works perfectly fine, I’m trying to stay away from hardcoding strings like that for obvious reasons.

is it a bug or am i missing something?

First, simply output all incoming data to the console and inspect their values:

Debug.Log(hit.transform.gameObject.layer);
Debug.Log(attacklayer.value);
Debug.Log(attacklayer);

Mask layers are bitwise values, not just some integer ordinal number. Therefore, one way is to convert it into a bit mask:

if (1 << hit.transform.gameObject.layer == attacklayer.value)
{

}
1 Like

While samana’s solution works for a layermask with a single layer, when you select multiple layers, this would not work. Here you should do the usual bitwise operation to check if a particular bit is set in the mask.

int mask = 1 << hit.transform.gameObject.layer;
if ((attacklayer.value & mask) != 0)

With this approach you can select as many layers in your attacklayer Layermask variable and any specified would work. It’s important to use the bitwise “and” & here, not the logical boolean “and” &&

So say the layer in question is layer with index “5”. When we do 1<<5 we get the value of 32 or in binary 0x00100000. When you select layer 5 and 7 in your attacklayer mask, it would look like this 0x10100000

So when you “and” them together you get:

0x00100000
0x10100000
----------
0x00100000

which gives you a result that is not 0. When the incoming layer would be layer 6, the mask would be 0x01000000 and the result of the and operation would be:

0x01000000
0x10100000
----------
0x00000000
1 Like

Thanks for your help, for some reason though I get this error (Operator ‘&’ cannot be applied to operands of type ‘int’ and ‘bool’) using this approach.

1 Like

You’ll need to add parenthesis around the bitwise operator.

if ((attacklayer.value & mask) != 0)
2 Likes

Thanks Guys this worked perfectly :smile:

1 Like

Maybe you’ll find this crash course on layers and bit masks useful.

1 Like

Yes, my bad :slight_smile: I’ve written the answer right here without checking. I’ve fixed my post so nobody copies broken code from here.