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.

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.

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:

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 “|”.

So it checks if the rayacast hit’s anything on layer 6 OR 7.

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store