unity3d LayerMask Structure


Example

The LayerMask structure is an interface that functions almost exactly like passing an integer to the function in question. However, its biggest benefit is allowing the user to select the layer in question from a drop-down menu in the inspector.

using UnityEngine;
class LayerMaskExample{

    public LayerMask mask;
    public Vector3 direction;

    void Start()
    {
        if(Physics.Raycast(transform.position, direction, 35f, mask))
        {
            Debug.Log("Raycast hit");
        }
    {
}

It also has multiple static functions that allow for converting layer names to indices or indices to layer names.

using UnityEngine;
class NameToLayerExample{

    void Start()
    {
        int layerindex = LayerMask.NameToLayer("Obstacle");
    {
}

In order to make Layer checking easy define the following extension method.

public static bool IsInLayerMask(this GameObject @object, LayerMask layerMask)
{
    bool result = (1 << @object.layer & layerMask) == 0;

    return result;
}

This method will allow you to check whether a gameobject is in a layermask (selected in the editor) or not.