Using Layermasks With Raycasting in Unity 2021

In this article we’ll briefly cover using layer masks in conjunction with raycasting.

I’ve set up a simple scene with 3 grey cubes named “Enemy” and 1 blue cube named “Player”.

I also have an empty game object named “PlayerInput” with the LayerMasks_PlayerInput script assigned to it.

We’ll add a new layer called “Enemy”.

Then we assign this new layer to each of our Enemy game objects.

Last, we can see similar raycast code for our input script as from previous articles.

The difference this time is that we have added a bitwise operation to the Physics.Raycast call.

What this section for the layerMask represents is assigning a “1” value in binary, or what can be thought of as “True” if it were a Boolean.

The “<<” can be thought of as “assigns” or assigning the value on the left side of the operator to the layer ID number on the right side of the operator.

Since our Enemy layer is on layer 6, the Layermask assignment is “1 << 6”.

So, now our script will take the mouse click input as a raycast, determine if a game object was “hit”, and if that game object is on the “Enemy” layer.

It will then change the “hit” game object’s color to red.

And there you have it.

Because the blue cube is the Player game object which has the Default layer, clicking on it has no effect.

Clicking on our Enemy game objects assigned to the Enemy layer however turns red as intended.

In the next article, we’ll use raycasting to create bullet holes!

--

--

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