Best way to set a GameObject layer programmatically?

In my game I have an ArmamentController, a Monobehaviour that attaches to Actors (players or enemies). This controller has a public LayerMask variable so that I can set the layer for the projectiles (for the collision matrix; friendly bullets don’t collide with the player, enemy bullets don’t collide with enemies). The really nice thing about this is that in the editor, I get the list of layers (as opposed to stringly typing, which sucks).

This, unfortunately, fails horribly with GameObject.layer, as the LayerMask is an object while GameObject.layer is an int. LayerMask provides the value getter, but that actually returns the bitmask, not the integer of the layer. There doesn’t seem to be a function that does this (and I’m not sure why - why not add it as a property to the LayerMask?)

I could get the integer value, but unfortunately the only way to inverse a bitshift function is to use a logarithm, and those are pretty expensive…so if there are a lot of shots, that’s something you don’t want, right?

Is there another Unity object type besides LayerMask? Layer, perhaps? Or something like that? Or am I forced to use the logarithm method (or some wacky loop or something) or resort to strings? Is there perhaps a built-in enumerator for this, or can I access the Layer list directly…?

Edit: I tried using the ToString() method of my LayerMask variable, hoping that behind the scenes it was using the [Enum] tag somewhere (like this question) but alas, that idea didn’t work either.

gameObject.layer = LayerMask.NameToLayer(“YourLayerName”);

Using LayerMask is correct. Just use the bitshift operators << and >>. No log required!