🔢

UNITY LAYERMASK & BITMASK GENERATOR

Visually select Unity physics layers to calculate their 32-bit bitmask integer value, binary bitflags, and generated C# code for Physics.Raycast, Physics2D, and LayerMask.GetMask.

SELECT ACTIVE LAYERS (0 - 31)

CALCULATED BITMASK 32-BIT UINT

INTEGER MASK VALUE
1
Hex: 0x00000001
BINARY BIT PATTERN (BITS 31 → 0)
00000000 00000000 00000000 00000001
C# BITWISE EXPRESSION
(1 << 0)

UNITY RAYCAST USAGE EXAMPLE (C#)

using UnityEngine;

public class RaycastWithLayerMask : MonoBehaviour
{
    // Exact layer mask computed from Khawajja Games Generator
    public LayerMask targetMask = 1; 

    void Update()
    {
        Ray ray = new Ray(transform.position, transform.forward);
        RaycastHit hit;

        // Perform raycast only against selected layer bitmask
        if (Physics.Raycast(ray, out hit, 100f, targetMask))
        {
            Debug.Log("Hit Target: " + hit.collider.gameObject.name);
        }
    }
}

HOW UNITY LAYERMASKS & BITWISE MATH WORK

Bit-Shift Syntax: (1 << Layer)

In Unity, layer numbers are indices from 0 to 31. However, physics query functions like Physics.Raycast expect an integer bitmask where bit $N$ is set to 1.

The bitwise shift operator (1 << N) takes the binary number 1 and shifts it left by $N$ places:

  • Layer 0: 1 << 0 = 1 (Binary: 0001)
  • Layer 1: 1 << 1 = 2 (Binary: 0010)
  • Layer 8: 1 << 8 = 256 (Binary: 100000000)

Bitwise Operations in Unity

Combine multiple layers using the bitwise OR operator |:

int mask = (1 << 8) | (1 << 9); // Layers 8 and 9

To collide with everything except a specific layer, use the bitwise NOT (invert) operator ~:

int mask = ~(1 << 2); // Everything except Layer 2