Raycasting With LayerMasks in Unity

Objective: Using a LayerMask with our Raycast to determine which game objects can change color when clicking on them.

When using Raycasts, LayerMasks come in handy as we can provide additional checks to determine which game objects we are able to click on, depending on which layer they are on.

Getting the Scene Setup

I have simply created a capsule to be used as the ‘Player’ and 2 cubes to be the ‘Enemy’.

I have then created a new layer in the Inspector and named this ‘Enemy’.

Make sure to set the ‘Enemycubes to the ‘Enemylayer.

Building Code

Option 1 — Using a String to Determine LayerMask

This is achieved through the GetMask(“Enemy”) static built-in method.

Option 2— Using Bitwise Operators to Determine LayerMask (more optimised)

There is a more optimised way of approaching this using bitmasks. Bitmasks represent the 32 layers of a LayerMask which are defined as ‘False’ or ‘True’. ‘Falserepresenting 0 and ‘Truerepresenting 1 respectively.

This is achieved through the use of bitwise left shift operator<<’.

1 << 6 

// This essentially means that we are setting bit 6 to the value of 1 (true)

Option 3— Using a LayerMask Serialized Dropdown Field in the Inspector

Our final solution is to create a LayerMask Serialized field in the Inspector so we can click the drop down menu and select ‘Enemy’ and this will be passed into the Physics.Raycast parameter.

Next Article



Passionate Unity Game Developer

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