- Home /
why is LayerMask different than gameObject.layer. - 256 = 8?
I have LayerMask on 1. user so Layer 8
public LayerMask TrueLayer = 256;
public LayerMask Layer;
void Start(){
Debug.Log(gameObject.layer); // 8
Layer.value = gameObject.layer;
Debug.Log(Layer.value);
}
Problem over here is I get value 8 WTF?!?!?
BUT when I look in inspector I see 2 different Layers:
what's going on?
why is layer not layer?
Answer by Jessy · Feb 19, 2014 at 06:22 PM
2 ^ 8 = 256
http://stackoverflow.com/questions/8447/what-does-the-flags-enum-attribute-mean-in-c
You can currently only have a Game Object associated with a single 1, of the 32 available slots, but other things in Unity can utilize all of the 1s and 0s.
e.g. https://docs.unity3d.com/Documentation/ScriptReference/Camera-cullingMask.html
yes I do understand all that, ...
but WHY can't it be
gameObject.Layer = 256; // to be 8 slot?
as 256 is only 1 layer
Ease of use. Bit flags aren't geared for ease of use; they're geared for efficiency. Because Unity was designed to only allow Game Objects to be in one layer, the logical thing to do was to make .Layer a property that sets the flag to 0x1 << value
. (Na$$anonymous$$g it .layer was not logical, and was designed to fit in with the illogical monstrosity of a language they created in hopes of drawing in more users.)
I think that's much more clear than what I think you're suggesting, which is either to throw an error when the value you provide requires more than one 1, or to only use the most significant bit.
Notice how the property is called "layer", not "layer$$anonymous$$ask".
ok thanks this explains it, ...
even tho I'd rather see it's always Layer$$anonymous$$ask
I guess you should add your last comment to your answer.
Answer by Vahradrim · Nov 30, 2015 at 06:54 PM
Men, just use this :
Mathf.Log(collisionlayerMask.value, 2)
It's that simple (I searched for a while for this so, here it is) (It's the logarithm of the number in base 2 -> it's the opposite of the 2^x function)
I don't comment something often but I was too amazed to see why people struggled so much with bit-twisting.. You're welcome :)
This doesn't answer the question at all. Yes, if you have a layermask with only a single layer active then you can use the logarithm, but you actually never need this. The moment you have an actual layermask with more than one layer it won't work. If you work with single layers you almost always work with layer indices and not a mask value. You usually convert a layer index into a mask way more often than the other way round.
However if you want a reliable way to convert a layermask into layer indices you might want to use:
public static List<int> Get$$anonymous$$askIndices(Layer$$anonymous$$ask a$$anonymous$$ask)
{
List<int> indices = new List<int>(32);
for(int i = 0; i < 32; i++)
{
if ((a$$anonymous$$ask.value & (1 << i)) > 0)
indices.Add(i);
}
return indices;
}