Skip to content

Rovsau/LayerMask-Explained

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

33 Commits
 
 
 
 
 
 
 
 

Repository files navigation

LayerMask Explained

Use NameToLayer() to get a layer's index.
It is used to set or compare an object's layer.

int layerIndex = LayerMask.NameToLayer("Default");
bool sameLayer = gameObject.layer == layerIndex;
gameObject.layer = layerIndex;

The other methods in Unity, such as Raycast(), require a LayerMask.
A LayerMask contains a 1 or 0 for all 32 layers.

Use GetMask() to create a LayerMask which includes all the layers specified.
Or use it to create masks with single layers, and use the OR | operator to create combinations between them.

LayerMask a = LayerMask.GetMask("Default");
LayerMask b = LayerMask.GetMask("Water");
LayerMask c = LayerMask.GetMask("Default", "Water");

LayerMask raycastLayers = a | b;  // The same as 'c'
Raycast script example
using UnityEngine;

public class LayerMaskScriptExample : MonoBehaviour
{
    public float distance;
    public LayerMask raycastLayers;

    private void Awake()
    {
        LayerMask a = LayerMask.GetMask("Default");
        LayerMask b = LayerMask.GetMask("Water");
        LayerMask c = LayerMask.GetMask("Default", "Water");

        raycastLayers = a + b;  // The same as 'c'
    }

    private void Update()
    {
        if (Physics.Raycast(transform.position, transform.forward, distance, raycastLayers))
        {
            Debug.Log("Hit something on a layer included in the mask!");
        }
    }
}

That is all which is needed to work with LayerMask in Unity.
Further reading is optional.

LayerMask Functions

Advanced (BitMask, Bit Shifting)

LayerMask Utilities

About

No description or website provided.

Topics

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors

Languages