Skip to content

Instantly share code, notes, and snippets.

@bitnenfer
Last active August 29, 2015 14:15
Show Gist options
  • Save bitnenfer/c6a37778fba4c9821b0e to your computer and use it in GitHub Desktop.
Save bitnenfer/c6a37778fba4c9821b0e to your computer and use it in GitHub Desktop.
Unity Rendering Sorting Layer
using UnityEngine;
using System.Collections;
namespace SortingOrder
{
[RequireComponent(typeof(Renderer))]
public class SortComponent : MonoBehaviour { }
}
using UnityEngine;
using UnityEditor;
using UnityEditorInternal;
using System.Reflection;
using System.Collections.Generic;
namespace SortingOrder
{
[CustomEditor(typeof(SortComponent), true)]
public class SortingOrderEditor : Editor
{
private string[] GetSortingLayerNames()
{
var internalEditorUtilityType = typeof(InternalEditorUtility);
PropertyInfo sortingLayersProperty = internalEditorUtilityType.GetProperty("sortingLayerNames", BindingFlags.Static | BindingFlags.NonPublic);
return (string[])sortingLayersProperty.GetValue(null, new object[0]);
}
private int GetSelectedID(string[] layerNames, Renderer renderer)
{
string currentLayer = renderer.sortingLayerName;
for (int index = 0; index < layerNames.Length; index++)
{
if (layerNames[index] == currentLayer)
{
return index;
}
}
return -1;
}
public override void OnInspectorGUI()
{
base.OnInspectorGUI();
Renderer renderer = ((SortComponent)target).renderer;
string[] layerNames = GetSortingLayerNames();
EditorGUILayout.LabelField("Sorting Layer", EditorStyles.boldLabel);
EditorGUI.indentLevel++;
EditorGUILayout.LabelField("Current Layer ID: ", renderer.sortingLayerID.ToString());
EditorGUILayout.BeginHorizontal();
EditorGUI.BeginChangeCheck();
int selected = EditorGUILayout.Popup("Layer Name:", GetSelectedID(layerNames, renderer), layerNames);
if (EditorGUI.EndChangeCheck())
{
renderer.sortingLayerName = layerNames[selected];
}
EditorGUILayout.EndHorizontal();
EditorGUILayout.BeginHorizontal();
EditorGUI.BeginChangeCheck();
int order = EditorGUILayout.IntField("Sorting Order: ", renderer.sortingOrder);
if (EditorGUI.EndChangeCheck())
{
if (order < 0)
{
order = 0;
}
renderer.sortingOrder = order;
}
EditorGUILayout.EndHorizontal();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment