ScriptReference/SortingLayer #620
Replies: 1 comment
-
|
Unity doesn't provide any tools for selecting a sorting layer from the editor on a custom script, and as the SortingLayer struct is not serializable, it will not show on the editor. Here's my recommended fix around: [Serializable]
public struct SortingLayerPicker
{
public int Id;
public static implicit operator string(SortingLayerPicker picker)
{
return SortingLayer.IDToName(picker.Id);
}
public static implicit operator int(SortingLayerPicker picker)
{
return picker.Id;
}
public int Value => SortingLayer.GetLayerValueFromID(Id);
}
#if UNITY_EDITOR
[CustomPropertyDrawer(typeof(SortingLayerPicker))]
public class SortingLayerPickerDrawer : PropertyDrawer
{
public override void OnGUI(Rect position, SerializedProperty property, GUIContent label)
{
var IdProp = property.FindPropertyRelative("Id");
var names = SortingLayer.layers.Select(x => x.name).ToArray();
int index = 0;
for (int i = 0; i < SortingLayer.layers.Length; i++)
if (IdProp.intValue == SortingLayer.layers[i].id)
{
index = i;
break;
}
index = EditorGUI.Popup(position, label.text, index, names);
IdProp.intValue = SortingLayer.layers[index].id;
}
}
#endifAdd this code on any script in your project, preferably a new one. Now, if you want to select a sorting layer from a custom MonoBehaviour, simply add a SortingLayerPicker field visible in the inspector, and automatically the inspector will display a pop up to choose a layer from. |
Beta Was this translation helpful? Give feedback.
0 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Uh oh!
There was an error while loading. Please reload this page.
-
ScriptReference/SortingLayer
https://docs.unity3d.com/ScriptReference/SortingLayer.html
Beta Was this translation helpful? Give feedback.
All reactions