Sorting Layer VS Layer Mask Scripting

If I define
LayerMask sortingLayerSelect;

In the editor I get a drop down list of Layers.

How can I replicate this for the sorting layers from the sprite rederer in 2d?

the default setting is to have no sorting layers… you will need to create some in order for something to show in the Sorting Layer drop down field of the sprite renderer inspector.

They show Up in the sortinglayer defatult dropdown. I want to add it to my script so you can select the sorting layer of my script without having to type it in.

You’re going to have to create a custom editor for this.

I’m assuming this field is just an int.

So create an attribute that inherits from PropertyAttribute in your regular scripts folder.

public class SortingLayerAttribute : PropertyAttribute
{

}

Then create a PropertyDrawer in your Editor scripts folder for that attribute:

[CustomPropertyDrawer(typeof(SortingLayerAttribute))]
public class SortyingLayerPropertyDrawer : PropertyDrawer
{
    override void OnGUI(Rect position, SerializedProperty property, GUIContent label)
    {
        //get the available layers, draw a popup with EditorGUI.Popup, update property with the info
    }
}

Now where you have a int field that is supposed to be a sorting layer, tag it with that attribute:

[SortingLayer()]
public int SortingLayer;

Here’s the documentation for PropertyDrawers:

And the documentation for EditorGUI.Popup:

Thank you! I am going to give it a shot.

It’s an old thread, but for those who find it, here is a working implementation for what was suggested above. For Unity 5.3+

Use like this:

[IsSortingLayer] public string sortingLayerName;

IsSortingLayerAttribute.cs

using UnityEngine;
public class IsSortingLayerAttribute : PropertyAttribute {}

Editor/IsSortyingLayerPropertyDrawer.cs

using UnityEngine;
using UnityEditor;

[CustomPropertyDrawer(typeof(IsSortingLayerAttribute))]
public class IsSortyingLayerPropertyDrawer : PropertyDrawer
{
  public override void OnGUI(Rect position, SerializedProperty property, GUIContent label)
  {
    int selected = -1;

    var names = new string[SortingLayer.layers.Length];
    for(int i=0; i<SortingLayer.layers.Length; i++)
    {
      names[i] = SortingLayer.layers[i].name;
      if(property.stringValue == names[i])
        selected = i;
    }

    EditorGUI.BeginProperty(position, label, property);
    position = EditorGUI.PrefixLabel(position, GUIUtility.GetControlID(FocusType.Passive), label);
    selected = EditorGUI.Popup(position, selected, names);
    EditorGUI.EndProperty();

    if(selected >= 0)
      property.stringValue = names[selected];
  }
}
6 Likes