Search Unity

LayerMask makes me going insane.

Discussion in 'Scripting' started by nbg_yalta, Apr 27, 2015.

  1. nbg_yalta

    nbg_yalta

    Joined:
    Oct 3, 2012
    Posts:
    378
    Ok, what I have:
    Code (csharp):
    1.  
    2. public LayerMask mask;    // Select layer mask in inspector;
    3. public GameObject obj;
    4.  
    5. //What I need is to assign mask to the obj layer in start
    6.  
    7. void Start()
    8. {
    9. obj.layer = mask;
    10. }
    11.  
    But how? I've tried a bunch of different conversions but with no luck. Any thoughts?
     
  2. Darkcoder

    Darkcoder

    Joined:
    Apr 13, 2011
    Posts:
    3,414
    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
    Code (csharp):
    1. using UnityEngine;
    2. #if UNITY_EDITOR
    3. using UnityEditor;
    4. #endif
    5.  
    6. public class LayerAttribute : PropertyAttribute
    7. {
    8. }
    9.  
    10. #if UNITY_EDITOR
    11. [CustomPropertyDrawer(typeof(LayerAttribute))]
    12. public class LayerDrawer : PropertyDrawer
    13. {
    14.     public override void OnGUI(Rect position, SerializedProperty property, GUIContent label)
    15.     {
    16.         property.intValue = EditorGUI.LayerField(position, label, property.intValue);
    17.     }
    18. }
    19. #endif
    To use this, simply mark your variable with [Layer], e.g.: [Layer]public iny MyCoolLayer;
     
  3. nbg_yalta

    nbg_yalta

    Joined:
    Oct 3, 2012
    Posts:
    378
    Thanks, will try it asap.