Search Unity

Feature Request LayerMask and Bit Twiddling - a Suggestion

Discussion in 'Scripting' started by halley, Jan 29, 2023.

  1. halley

    halley

    Joined:
    Aug 26, 2013
    Posts:
    2,443
    After seeing a few threads with confusion over LayerMask bit-twiddling, and the difference between layer NUMBER and layer MASK concepts, I thought I'd share a little snippet from my collection, which I still wish would be added to the official API.

    Code (CSharp):
    1. using UnityEngine;
    2. using System.Runtime.CompilerServices;
    3.  
    4. public static class HalleysTotallyCoolUnityExtensionMethods
    5. {
    6.     // ...
    7.  
    8.     [MethodImpl(MethodImplOptions.AggressiveInlining)]
    9.     public static LayerMask WithLayer(this LayerMask mask, int layer)
    10.     {
    11.         return mask.value | (1 << layer);
    12.     }
    13.     [MethodImpl(MethodImplOptions.AggressiveInlining)]
    14.     public static LayerMask WithoutLayer(this LayerMask mask, int layer)
    15.     {
    16.         return mask.value & ~(1 << layer);
    17.     }
    18.  
    19.     public static LayerMask WithLayer(this LayerMask mask, string layer)
    20.     {
    21.         return mask.value | LayerMask.GetMask(layer);
    22.     }
    23.  
    24.     public static LayerMask WithoutLayer(this LayerMask mask, string layer)
    25.     {
    26.         return mask.value & ~LayerMask.GetMask(layer);
    27.     }
    28.  
    29.     // ...
    30. }
    31.  
    Thanks to the way LayerMask already implicitly allows for conversions to the integer type, these functions can easily stack and interoperate.

    Code (CSharp):
    1.  
    2.     public LayerMask myMask;
    3.     // ...
    4.     myMask = myMask.WithoutLayer(6).WithoutLayer("Ignore Raycast");
    5.  
     
    chemicalcrux likes this.