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.
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”.
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.
This can also be modified very easily to account for multiple desired layer subsets.
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.
Which in turn makes the code logic much more readable (in my personal opinion)