LayerMask makes me going insane.

Ok, what I have:

public LayerMask mask;    // Select layer mask in inspector;
public GameObject obj;

//What I need is to assign mask to the obj layer in start

void Start()
{
obj.layer = mask;
}

But how? I’ve tried a bunch of different conversions but with no luck. Any thoughts?

A LayerMask allows you to select multiple layers and gives you the bit mask for it, this is useful for raycasting and filtering GameObjects and such. However, the GameObject’s layer is a layer index, so you can’t always convert between them.

Unfortunately, Unity doesn’t come with a LayerMask style struct to make this easier, so you must use the EditorGUI.LayerField to draw the dropdown layer list. But you can bundle that into a property drawer to make it easily usable, for example:

LayerAttribute.cs

using UnityEngine;
#if UNITY_EDITOR
using UnityEditor;
#endif

public class LayerAttribute : PropertyAttribute
{
}

#if UNITY_EDITOR
[CustomPropertyDrawer(typeof(LayerAttribute))]
public class LayerDrawer : PropertyDrawer
{
    public override void OnGUI(Rect position, SerializedProperty property, GUIContent label)
    {
        property.intValue = EditorGUI.LayerField(position, label, property.intValue);
    }
}
#endif

To use this, simply mark your variable with [Layer], e.g.: [Layer]public iny MyCoolLayer;

Thanks, will try it asap.