Featured Video Play Icon

Unity Custom Editor Sorting Layer Helper

Now that I’m in-between jobs I thought it would be a good time to learn some parts of Unity I’ve never touched before. One of them was custom editor scripts, so I combined that with a helper class to expose all sorting layers in any given scene and came up with this mini-project. The video above documents the process I went through, the current implementation, and suggested improvements for further expansion. You can also view the scripts mentioned below.


using UnityEngine;
using System.Collections;

[ExecuteInEditMode]
public class ChangeSortingOptions : MonoBehaviour 
{
    public SpriteRenderer[] spriteRenderers;
    public int rendererNum;
  
    void Start () 
    {
        GetSpriteRenderers();
    }

    public void GetSpriteRenderers()
    {
        spriteRenderers = (SpriteRenderer[])Resources.FindObjectsOfTypeAll(typeof(SpriteRenderer));
        rendererNum = spriteRenderers.Length;
    }
}


using UnityEngine;
using UnityEditor;
using UnityEditorInternal;
using System;
using System.Reflection;

[CustomEditor(typeof(ChangeSortingOptions))]
public class ChangeSortingOptionsEditor : Editor {

    private string[] sortingLayerNames;
    private int choiceIndex = 0;
    private Vector2 scrollPos;

    public override void OnInspectorGUI()
    {
        ChangeSortingOptions myTarget = (ChangeSortingOptions)target;
        sortingLayerNames = GetSortingLayerNames();

        if (GUILayout.Button("Update"))
        {
            myTarget.GetSpriteRenderers();
        }

        EditorGUILayout.Space();
        scrollPos = EditorGUILayout.BeginScrollView(scrollPos);

        for (int i = 0; i < myTarget.rendererNum; i++)
        {
            if (myTarget.spriteRenderers[i] != null)
            {
                EditorGUILayout.LabelField(myTarget.spriteRenderers[i].name, EditorStyles.boldLabel);

                for (int j = 0; j < sortingLayerNames.Length; j++)
                {
                    if (myTarget.spriteRenderers[i].sortingLayerName == sortingLayerNames[j]) choiceIndex = j;
                }

                choiceIndex = EditorGUILayout.Popup("Sorting Layer", choiceIndex, sortingLayerNames);
                myTarget.spriteRenderers[i].sortingLayerName = sortingLayerNames[choiceIndex];

                myTarget.spriteRenderers[i].sortingOrder = EditorGUILayout.IntField("Order In Layer", myTarget.spriteRenderers[i].sortingOrder);
                EditorGUILayout.Space();
            }

        }

        EditorGUILayout.EndScrollView();

    }

    public string[] GetSortingLayerNames()
    {
        Type internalEditorUtilityType = typeof(InternalEditorUtility);
        PropertyInfo sortingLayersProperty = internalEditorUtilityType.GetProperty("sortingLayerNames", BindingFlags.Static | BindingFlags.NonPublic);
        return (string[])sortingLayersProperty.GetValue(null, new object[0]);
    }
}