layer = layerMask (which is set in Inspector)

Howdy,

I have want to set the layer for an gameObject in the inspector (instead of using a number or string in the code). So I added this to my object’s script:

[SerializeField] private LayerMask previewLayer;

And selected the right layer for it in the inspector.

And now in the object’s c# script I want to set the layer of the GameObject to the previewLayer.

gameObject.layer = previewLayer.value;
or 
gameObject.layer = previewLayer;

But I get this error: “A game object can only be in one layer. The layer needs to be in the range [0…31]”. How to solve this?
Tia

I know it is an old question, but in case someone still needs it.
A much easier way to set layer from layer mask from the inspector:

int layer = (int) Mathf.Log(layerMask.value, 2);

:slight_smile:

Hi everyone, thanks for replying,

I think I found the answer in this thread https://forum.unity3d.com/threads/get-the-layernumber-from-a-layermask.114553/ .

I now use this little helper function to pass a LayerMask and get an int from it back (within a static class):

public static int layermask_to_layer(LayerMask layerMask) {
		int layerNumber = 0;
		int layer = layerMask.value;
		while(layer > 0) {
			layer = layer >> 1;
			layerNumber++;
		}
		return layerNumber - 1;
	}

I think it works, if it appears to be buggy or such I will edit this answer.

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

or

gameObject.layer = x; (where x is an integer equal to your layer number)

Your solution does not work because LayerMask is a struct, not an int.
Though I would have thought that as LayerMask.value returns an int that it should have worked. Except if your layerMask contained multiple layers

as meat5000 said, As far as I know its an int and can very simply be used for multiple layers.
You can directly interpret which Bits are on or off from a single decimal number. You can use this online tool for conversion http://www.calculatorology.com/decimal-to-binary-converter/

It’s an old one indeed but I think this may be the most optimised way, I made it into a little extension method so you can simply use someLayerMask.ToSingleLayer(); (save this as e.g. LayerMaskExtensions.cs).

 using UnityEngine;
 public static class LayerMaskExtensions
 {
     public static int ToSingleLayer(this LayerMask mask)
     {
         int value = mask.value;
         if (value == 0) return 0;  // Early out
         for (int l = 1; l < 32; l++)
             if ((value & (1 << l)) != 0) return l;  // Bitwise
         return -1;  // This line won't ever be reached but the compiler needs it
     }
 }

Another option.
With this, you can at least type the NAME of the layer in the inspector.

 public string layerNameWeTypedInInspector;
...
 gameObject.layer = LayerMask.NameToLayer(layerNameWeTypedInInspector);

Then you see i set the layer of some gameObject.