Unity: Checking a GameObjects layer against multiple LayerMasks

Continuing on from the previous post about Tags vs Layers this post leads into one of my favourite C# coding features; Extension Methods.

Here we see a Raycast checking for hits against multiple possible layers.

Unity Code Example - Raycast Multiple Layers
Detect a Raycast hit filtered with multiple Layers

In this example we are scanning ahead of a moving projectile and triggering the Destroy function on both the projectile and the GameObject that it “hits”.

Unity Code Example - Raycast Multiple Layers with sample code
Example of a “projectile” hitting another GameObject

This will work fine, although in practice having every Wall, Enemy or Player object destroyed on contact with the projectile may not be what we want.

What about if we only want the projectile to destroy enemies but still destroy itself if it hits a wall or the player. Well we still need the Raycast to detect all of the collidable layers that we defined – if we just limit the Raycast to the Enemies layer, it will not detect walls or players, and so will be able to “hit” and “destroy” Enemies behind Walls and Players.

So once we have the “hit” from the Raycast, we now need to check the layer of the object returned to only perform the “kill” action if it is an Enemy. As the LayerMask is a bitmask we can do a bit shift operation on the GameObjects Layer to then  compare with our desired Enemies only LayerMask.

Unity Code Example - Raycast Multiple Layers and check single layer with sample code
Check the projectile hits the “Enemy” and destroy it

This can also be modified very easily to account for multiple desired layer subsets.

Unity Code Example - Raycast Multiple Layers and check multile layers with sample code
Projectile now kills “Enemies” and “Players”

One last step I like to take;

Bitwise operations are not the most readable, and in any Unity project utilising multiple Layers you are likely to implement these checks multiple times. I like to extract this functionality into an Extension Method for ease of reuse and contextual readability.

Unity Code Example - LayerMask ExtensionMethod
LayerMask Extension Method

Which in turn makes the code logic much more readable (in my personal opinion)

Unity Code Example - LayerMask ExtensionMethod usage
More readable code logic within the Raycast

One thought on “Unity: Checking a GameObjects layer against multiple LayerMasks

Add yours

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

Blog at WordPress.com.

Up ↑

%d bloggers like this: