Skip to content

Instantly share code, notes, and snippets.

@unitycoder
Last active June 20, 2024 19:58
Show Gist options
  • Save unitycoder/cb887da3be89458968101a92cf61720b to your computer and use it in GitHub Desktop.
Save unitycoder/cb887da3be89458968101a92cf61720b to your computer and use it in GitHub Desktop.
Check if GameObject is in Layer or check if Layer is in LayerMask
// https://forum.unity.com/threads/extension-methods-for-layermask.1605513/
public static void Add(ref this LayerMask mask, int layer)
{
    mask |= (1 << layer);
}
 
public static void Remove(ref this LayerMask mask, int layer)
{
    mask &= ~(1 << layer);
}
 
public static bool Contains(this LayerMask mask, int layer)
{
    return (0 != (mask & (1 << layer)));
}
 
public static bool Contains(this LayerMask mask, GameObject gob)
{
    if (gob == null)
        return false;
    return (0 != (mask & (1 << gob.layer)));
}
 
public static bool Contains(this LayerMask mask, Component component)
{
    if (component == null)
        return false;
    return (0 != (mask & (1 << component.gameObject.layer)));
}
// https://forum.unity.com/threads/checking-if-a-layer-is-in-a-layer-mask.1190230/#post-9880839
public static bool IsInLayerMask(GameObject obj, LayerMask mask) => (mask.value & (1 << obj.layer)) > 0;
public static bool IsInLayerMask(int layer, LayerMask mask) => (mask.value & (1 << layer)) > 0;
@unitycoder
Copy link
Author

Check if Layer Exists (by name), Assign Gameobject to layer using LayerMask
https://gist.github.com/unitycoder/65f604895f1699b92af1ba7762bfab45

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment