Check if Layer is in Layermask?

How can you tell if a LayerMask contains a given layer.

A C# solution that elegantly results in a bool is:

layermask == (layermask | (1 << layer))

Create a static class with extension methods as you go along. You’ll find lots of functionality you wish was included in the frameworks. Might as well add it yourself!

using UnityEngine;
using UnityEngine.Events;

public static class UnityExtensions{

/// <summary>
    /// Extension method to check if a layer is in a layermask
    /// </summary>
    /// <param name="mask"></param>
    /// <param name="layer"></param>
    /// <returns></returns>
    public static bool Contains(this LayerMask mask, int layer)
    {
        return mask == (mask | (1 << layer));
    }
}

Then just use it like:

if(_layerMask.Contains(otherLayer))
{
     //Do stuff
}

var layermask : LayerMask;
var layer : int;

function Start () {
    if (layermask.value; 1<<layer) {
        Debug.Log ("Layer is in layer mask");
    }
}

if ((layerMask.layer & (1<<layerToCheck)) != 0)

Simpler and more straight forward if a single bit is true on both the mask and the layer to check, it contains the layer and returns non 0.

There are two solutions provided above, one with “|” and one with “&”. The difference would be what you want the result to be when layer == 0 (Default layer), in which case the “|” routine returns true and the “&” routine returns false.

I my case I want to detect collision with a specific layer and in that case layer 0 should return false, so the “&” routine is the correct one for me. Put in a static method:

public static bool Contains(this LayerMask mask, int layer)
{
       return ((mask & (1 << layer)) != 0)
}