LayerMask > GameObject.layer

Embarrassing problem. Anyway. I have a LayerMask that always only has 1 layer activated. How do I get the corresponding integer GameObject layer for this mask value?

Example
00000000000000000000000010000000

This value is 128, but I need the offset which is 8. How do I get this?

Thank you.

NOTE! This is not about getting the layermask for gameobject layer. It’s the other way around.

Doing retarded solution until someone replies with something better

    public static int GetGameObjectLayer(this LayerMask mask)
    {
        for (int i = 0; i < 32; ++i)
        {
            if (((1 << i) & mask.value) > 0)
            {
                return i;
            }
        }

        return -1;
    }
1 Like

When you have a layermask with a single layer only, the value (eg 128) is 2 raised to the power of that layers number (in this case 2^7 )
What you want is to ask “What power must I raise 2 by to get x”
Luckily, this is what Log does
layer = Mathf.Log(value, 2)
Nb. It returns a float, you might want/need to cast to an int

This will fail when the mask has more layers toggled

ps you said it was 8, but the right-most bit is bit 0, layer zero

2 Likes

Edit: I didn’t check out your code before I wrote this because you said it was retarded, causing me to skip over it before trying to help. That is “retarded”, but at least now I know more about myself. Thanks. I will try to avoid making the same mistake in the future.

At least maybe the nullable and the cross-platform calculation of int’s bits will help you.

public static class IntExtensions {
    public static int? GetIndexOfLowestTrueBit(this int flag) {
        for (var index = 0; index < sizeof(int) * 8; index++)
            if ((flag & 1) == 1) return index;
            else flag >>= 1;

        return null;
    }
}
2 Likes

Its all based 2 so its simple math really, you can either bit shift or use Algebra…

2^x = LayerMask.value

x = Log(LayerMask.value) / Log(2). Where log represents Log base e or Natural Log. I solved this problem today.

1 Like