Layer Masks in Unity
Layer masks allow us to essentially block or allow interactions with different objects. As for what a layer mask is specifically, per the documentation:
“A GameObject can use up to 32 LayerMasks supported by the Editor. The first 8 of these Layers
are specified by Unity; the following 24 are controllable by the user.” https://docs.unity3d.com/ScriptReference/LayerMask.html
You can create a new layer by going to the Layer dropdown in the editor and selecting “Add Layer…”
This pulls up the list of layers, and here we can create new layers for use to use.
You can grab the layer the mask by it’s name, but the more optimal way to do it is with the bitmask .
To explain bitmasks, we need to use a 32 bit integer.
0000 0000 0000 0000
0000 0000 0000 0000 <- it starts from the bottom right.
So, to get to layer 6, our enemy layer, we have to count over 6 characters not including spaces, and set it to 1. This means only layer 6 will be detectable by our raycast.
0000 0000 0000 0000
0000 0000 0010 0000
With this, we can specifically control which layers our raycast can and cannot hit, it’s much more effeciant that checking against the names of several layers.
So now, with oru raycast we do:
Physics.Raycast(rayOrigin, out var hitInfo, Mathf.Infinity, 1 << 6)
At there end is where were passing in what layers the racyast can hit, essentially were telling Unity to make character 6 in that 32bit integer, into a 1. “<<” means to bit shift, in this case shifting bit 6 into a 1.
So to flag multiple layers we need to use an or statement, which is “|”.
Physics.Raycast(rayOrigin, out var hitInfo, Mathf.Infinity, 1 << 6 | 1 << 7)
So it checks if the rayacast hit’s anything on layer 6 OR 7.