- Home /
How to get the layermask Value ?
Hi,
So i read the documentation but I didn't understood that much, and couldn't fix my problem.
Actually I have this
public LayerMask defaultLayer;
public LayerMask reversedLayer;
I would like to change the layer in a fuction
void Reverse()
{
Debug.Log(reversedLayer.value >> 1);
if (reversed) {
gameObject.layer = defaultLayer.value >> 1;
}
else
{
gameObject.layer = reversedLayer.value >> 1;
}
reversed = !reversed;
}
I tried many solutions, but i always have this :
"A game object can only be in one layer. The layer needs to be in the range [0...31]"
How can i fix it?
thanks
Answer by maccabbe · Nov 27, 2015 at 06:17 PM
First, let's go over how layers and layermasks work.
A layermask is a group of layers, it can contain no, one, multiple, or all layers. This is done with layers having 32 possible values, 0 to 31, and layersmasks having 32 bits (0 or 1), i.e. 00001111000011110000111100001111. Every bit that is 1 means a layer is in the layermask.
Next, let's go over how left/right shift operators (<>) work. x << y moves all the bits in x left y times. For instance: 101<<2 = 10100. This is useful to convert layers to a layermask. Layer 0 is the 0th bit in a layermask so you can use 1<<0 to get the right bit while layer 31 is the 31th bit in a layermask so you can use 1<<31. Bitwise operations are very inexpensive so converting from layer to layermask is very cheap and then bitwise operations can be used to get the mask you want. I.e. (1<<0) | (1<<31) is the layermask with bits 0 and 31 set to 1.
In your code you are attempting to convert a layermask to a layer. However a layermask can have zero or multiple layers so this doesn't make sense. The method you are using, right shifting 1 bit, also doesn't make sense. Supposing that a layermask only has the 16th layer you start with 00000000000000010000000000000000 and end with 00000000000000001000000000000000 instead of 16. Your Debug.Log(reversedLayer.value >> 1);
would print the value in decimal which is 32768.
I would suggest not using layermasks if you want to use layers, Instead use strings/ints. For instance if your layers are called "Default" and "Reversed" you can use the following:
public int defaultLayer;
public int reversedLayer;
void Start()
{
defaultLayer = LayerMask.NameToLayer("Default");
reversedLayer = LayerMask.NameToLayer("Reversed");
}
void Reverse()
{
Debug.Log(reversedLayer);
if (reversed)
{
gameObject.layer = defaultLayer;
}
else
{
gameObject.layer = reversedLayer;
}
reversed = !reversed;
}
Answer by guneyozsan · Apr 05, 2017 at 03:21 PM
A quick and dirty way which works if you have only a single layer in your mask.
layerNumber = Mathf.Log(myLayer.value, 2)