在Unity开发过程中,可能会对旧资源进行批量修改,一个个手动修改费人费事,所以催生出了一堆批量工具。
分享一下在此过程中绘制 Sorting Layer 面板的代码脚本。
示意图:
在 EditorGUI 和 EditorGUILayer 中内置了 SortingLayerField 方法,但在外部使用比较麻烦,所以直接获取所有的 SortingLayer 名字,之后在GUI中进行绘制。
在绘制时有两种弹出方式,EditorGUILayout.Popup() 和 EditorGUILayout.DropdownButton(),在使用 EditorGUILayout.DropdownButton() 时需要动态创建 GenericMenu 选项菜单。
GenericMenu的具体用法可以翻阅官方文档。
完整代码:
using UnityEditor;
using UnityEngine;public class SortingLayerEditor : EditorWindow
{ private int _selectIndex = 0;private string[] _sortingLayerNames;private string _currentLog1, _currentLog2;[MenuItem("Tools/SortingLayerEditor")]private static void ShowWindow(){GetWindow<SortingLayerEditor>("SortingLayerEditor");}private void OnEnable(){// 初始化 SortingLayerNames// 如果需要实时获取 SortingLayerNames,请将下列代码放到OnGUI中_sortingLayerNames = new string[SortingLayer.layers.Length];for (var i = 0; i < SortingLayer.layers.Length; i++){_sortingLayerNames[i] = SortingLayer.layers[i].name;}}private void OnGUI(){// 绘制 SortingLayerNames// 方式一GUILayout.Label("方式一:");EditorGUI.BeginChangeCheck();_selectIndex = EditorGUILayout.Popup(new GUIContent("SortingLayer","SortingLayer < 0.0 >"), _selectIndex, _sortingLayerNames);if (EditorGUI.EndChangeCheck()){var layerName = _sortingLayerNames[_selectIndex];_currentLog1 = $"方式一 selectIndex: {_selectIndex}, SortingLayerName: {layerName}, ID:{SortingLayer.NameToID(layerName)}";Debug.Log(_currentLog1);}GUILayout.Space(4);// 方式二GUILayout.Label("方式二:");EditorGUILayout.BeginHorizontal();EditorGUILayout.LabelField(new GUIContent("SortingLayer","SortingLayer < 0.0 >"),GUILayout.Width(148));if (EditorGUILayout.DropdownButton(new GUIContent(_sortingLayerNames[_selectIndex]), FocusType.Passive)){// 动态添加菜单项var menu = new GenericMenu();for (var i = 0; i < _sortingLayerNames.Length; i++){var index = i;// 参数说明// 1. 菜单项的显示内容// 2. 是否选中// 3. 选中事件// 4. 选中事件参数menu.AddItem(new GUIContent(_sortingLayerNames[index]),_selectIndex == index,OnMenuSelected, index);}menu.ShowAsContext();}EditorGUILayout.EndHorizontal();GUILayout.Space(10);GUILayout.Label(_currentLog1);GUILayout.Label(_currentLog2);}/// <summary>/// 菜单项的选中事件 /// </summary>/// <param name="obj">选中事件参数</param>private void OnMenuSelected(object obj){_selectIndex = (int)obj;var layerName = _sortingLayerNames[_selectIndex];_currentLog2 = $"方式二 selectIndex: {_selectIndex}, SortingLayerName: {layerName}, ID:{SortingLayer.NameToID(layerName)}";Debug.Log(_currentLog2);}
}