Unity3D LayerMask 'bool Includes(int layer)' Extension Method
The fastest way to check if a GameObject in Unity is of a certain type is by using a LayerMask. Unfortunately, Unity does not offer a simple API to take advantage of this.
So let's create one.
Goal:
if(layerMask.Includes(layer))
...
The code:
public static class LayerMaskExtensions
{
public static bool Includes(
this LayerMask mask,
int layer)
{
return (mask.value & 1 << layer) > 0;
}
}
Usage example:
[SerializeField]
LayerMask layerMask;
protected void OnCollisionEnter(
Collision collision)
{
if(layerMask.Includes(collision.gameObject.layer))
{
// do stuff
}
}
How Do LayerMasks Work?
LayerMasks are stored as an integer, but represent any combination of Layers in your game. Layers are also integers... so how does that work?
Unity only supports up to 32 layers. An integer is 32 bits. A LayerMask simply allocates one bit for each layer, where 0 means that layer is not included, and 1 means that it is.
For example
Let's simplify and assume Unity supports only 4 layers. For example. the following LayerMask
0110
Means:
- Layer 0: not included
- Layer 1: included
- Layer 2: included
- Layer 3: not included
What is a C# extension method?
Extension methods are effectively a way of adding additional methods to a class or struct you don't own. In this example, Unity has a struct 'LayerMask'. That struct does not offer an easy way to determine if a Layer is part of that LayerMask.
Using extensions, we are able to create an 'Includes' method that can then be used as if Unity had written it for us. This allows us to focus on intent and forget the gory details.
For example
This statement:
if((layersToKill.value & 1 << gameObjectWeJustHit.layer) > 0)
...
Can now be written like so, which should be easier for people to follow.
if(layersToKill.Includes(gameObjectWeJustHit.layer))
...