Unity3D LayerMask 'bool Includes(int layer)' Extension MethodsteemCreated with Sketch.

in #unity3d7 years ago (edited)

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))
    ...
Sort:  

Let me know if there are any questions!

Congratulations @hardlydifficult! You have completed some achievement on Steemit and have been rewarded with new badge(s) :

You published your First Post
You made your First Vote
You got a First Vote
You made your First Comment

Click on any badge to view your own Board of Honor on SteemitBoard.
For more information about SteemitBoard, click here

If you no longer want to receive notifications, reply to this comment with the word STOP

By upvoting this notification, you can help all Steemit users. Learn how here!

Coin Marketplace

STEEM 0.18
TRX 0.16
JST 0.030
BTC 67167.55
ETH 2610.59
USDT 1.00
SBD 2.67