I have a script that changes the sorting layer on start up based on values I defined in the editor.
Here is the script :
using UnityEngine;
using System.Collections;
public class ZHK_SetSortingLayer : MonoBehaviour {
// Use this for initialization
public string sortingLayerName;
public int sortingOrder;
void Start () {
renderer.sortingLayerName = sortingLayerName;
renderer.sortingOrder = sortingOrder;
}
}
Now I dont want to run the game each time just to see the effects of that script. So I was wondering if someone could show me how to write an editor script to update the sorting layer automatically in the editor.
} If you want to add new sorting layer by taping in the field, it will be different code. P.S. I am not allowed to answer twice, this why i edit my previos answer.
[myNameSpace.SortingLayer]
public string sortingLayer;
Code:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEditor;
namespace myNameSpace
{
public class SortingLayerAttribute : PropertyAttribute
{
[CustomPropertyDrawer(typeof(SortingLayerAttribute))]
public class SortingLayerDrawer : PropertyDrawer
{
public override void OnGUI(Rect position, SerializedProperty property, GUIContent label)
{
string[] sortingLayerNames = new string[SortingLayer.layers.Length];
for (int a = 0; a < SortingLayer.layers.Length; a++)
sortingLayerNames[a] = SortingLayer.layers[a].name;
if (property.propertyType != SerializedPropertyType.String)
{
EditorGUI.HelpBox(position, property.name + "{0} is not an string but has [SortingLayer].", MessageType.Error);
}
else if (sortingLayerNames.Length == 0)
{
EditorGUI.HelpBox(position, "There is no Sorting Layers.", MessageType.Error);
}
else if (sortingLayerNames != null)
{
EditorGUI.BeginProperty(position, label, property);
// Look up the layer name using the current layer ID
string oldName = property.stringValue;
// Use the name to look up our array index into the names list
int oldLayerIndex = -1;
for (int a = 0; a < sortingLayerNames.Length; a++)
if (sortingLayerNames[a].Equals(oldName)) oldLayerIndex = a;
// Show the popup for the names
int newLayerIndex = EditorGUI.Popup(position, label.text, oldLayerIndex, sortingLayerNames);
// If the index changes, look up the ID for the new index to store as the new ID
if (newLayerIndex != oldLayerIndex)
{
property.stringValue = sortingLayerNames[newLayerIndex];
}
EditorGUI.EndProperty();
}
}
}
}
}