- Home /
How to get all layers included in a LayerMask?
I want to use LayerMasks in my script, but not for raycasting. I can make a public LayerMask variable which will appear in the inspector, but I'm not sure how to get the layer information out of the LayerMask.
In the end, I want something like this:
// whether the layer was selected in the inspector or not
bool[] layersArray = myLayerMask.GetLayers();
for(int i = 0; i < layersArray.length; i++) {
// do something with the layers
}
Answer by brunocoimbra · Jan 29, 2016 at 02:31 AM
Can't test right know, but try that:
[SerializeField]
private LayerMask layerMask;
private bool[] hasLayers = new bool[32];
private void CheckMasks()
{
for (int i = 0; i < 32; i++)
{
if (layerMask == (layerMask | (1 << i)))
{
hasLayers [i] = true;
}
}
}
EDIT: Already tested and working!
EDIT2: Here is two LayerMask extensions to help! Just create a c# script "LayerMaskExtensions" and copy paste the code.
public static class LayerMaskExtensions
{
public static bool HasLayer(this LayerMask layerMask, int layer)
{
if (layerMask == (layerMask | (1 << layer)))
{
return true;
}
return false;
}
public static bool[] HasLayers(this LayerMask layerMask)
{
var hasLayers = new bool[32];
for (int i = 0; i < 32; i++)
{
if (layerMask == (layerMask | (1 << i)))
{
hasLayers[i] = true;
}
}
return hasLayers;
}
}
To use it:
public LayerMask layerMask;
public int layer;
void Method()
{
bool hasLayer = layerMask.HasLayer(layer);
bool[] hasLayers = layerMask.HasLayers();
}
Thank you! That was a very good answer. And now I know about extension methods :D
Answer by Bunny83 · Jan 29, 2016 at 02:45 AM
Uhm it's not really clear what you want to do with the layer information. The LayerMask struct can only handle the layers defined in the tag / layer manager. A layermask is simply an uint value which represents a bit mask where each bit of the 32 bit number represent one layer.
So a value of "6" would be: 00000110 in binary. As you can see bit 1 and 2 are set if you start counting at 0.
You can use usual bit operations to check for a specific bit in a bit mask.
uint bitMask = 0x00e5; // 0000 0000 1110 0101
if ((bitMask & (1 << 3)) > 0) // check if bit 3 is set. In this case it is not set. Keep in mind the lowest bit is 0
bitMask |= 1<<4; // set bit 4 --> 0001 0000
// bitMask now contains -> 1111 0101
See the following posts for more information:
Answer by MrBalin · Nov 05, 2019 at 12:30 AM
if you want to check against all layers, I found this substitute works: Physics.DefaultRaycastLayers
Answer by sj631 · Sep 01, 2021 at 10:24 AM
LayerMask originalLayerMask = 2 | 4;
LayerMask layerMaskToCheck = 2;
LayerMask combinedLayerMask = originalLayerMask | layerMaskToCheck;
if (combinedLayerMask.value == originalLayerMask.value)
Debug.Log(layerMaskToCheck.value +" layer Found");
You can try this but keep raycast and collision layers different for performance reasons.