Unity Tip: Converting a LayerMask to a Layer index

Post date: 03-May-2015 00:49:43

Unity's layers offer a great way to filter game objects - for rendering or physics purposes. So my object creation scripts need to be able to assign objects to layers when they're created, but often I want to bake the layer index or layer name into the script, I want to specify it in the editor.

Unity's LayerMask attribute works nicely for this, but despite only permitting you to select one layer it still gives you a bit mask, not a layer index - so instead of index 9, it gives you 512 - the bit mask that only includes the ninth bit.

Any first year comp sci student should be able to tell you how to extract the index, but for those who (like me) struggled a bit:

LayerMask mask = LayerMask.NameToLayer("MyMask");

object.layer = Mathf.RoundToInt(Mathf.Log(mask.value, 2);

(Thanks to Amanda for her services as chief rubber duck on this.)