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.
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:
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.