Layer Masks in Unity

Suleiman Abdullah
3 min readMar 31, 2023

--

Objective: Understand Layer Masks in Unity.

Layer Masks in Unity Specifies Layers to use in physics dot Raycast. Also, a layer mask is a bit Mask which means Bitmasks represent the 32 Layers and define them as true or false.

To see those layers select any object <Inspector<layer, and choose add layer option this will open all unity layer masks.

In this step I will add 3 cubes to the scene, then I will add two layer masks which are player and enemy, and assign enemies to the two cubes.

Unity layer masks use bit shift operation to turn the layer on or off. These layers are presented by 8 bits numbers which give us a total of 32 bits of Zero and one.

0000 0000 0000 0000 0000 0000 0000 0000

Bit shift Operation

To perform this operation we put the bit number to the left and the layer number to the right then we put a double-less equal sign in the center, which means we are turning this layer on if we put one to the left or off if we put zero to the left.

Here is the bit shift 1<<7, this means we are taking this layer 7 which means all bits are off on this layer 0000 0000 0000 0000 0000 0000 0000 0000 then count from right to left seven times, on the seven-bit we put one which means we have turned that layer to on.

After doing a bit shift of 1<<7 the layer binary will be like this 0000 0000 0000 0000 0000 0000 0100 0000.

In this step, we want to do a bit shift in code, open the Player script and do a bit shift in physics dot Raycast. After that, we perform the logic we want for that object.

This show we can shoot at the enemy using ray cast and ignore the player

Another way we can create a layer mask variable and serialize it, then go to the editor select those objects, then click the drop-down button, and choose that layer. Then remove the bit shift operation and replace it with the name of the layer mask variable

In this step, select those enemy objects <Inspector<Maks, click dropDown, and choose the layer mask name.

Last we need to make sure we reset our bool to false to make sure the object changes color when clicked.

The Best Practice when using Layer mask is to use bit shift, cos this allow us to use more than one layer and perform logic for different object with different layer.

This is a layer mask let's see the result for the second option.

--

--

Suleiman Abdullah

Self taught Unity Developer, who is passion about making games ,and he loves Math For Game Development