拓展编辑器(十八)_源生自定义菜单
MenuItem是依托于Unity编辑器的菜单栏,换句话说就是无法设置它的位置。如果希望菜单的位置出现时更灵活的话,可以调用源生组定义菜单的方法。比如,可以在Scene视图中点击鼠标右键,此时会弹出一组源生自定义菜单。代码如下所示:
using UnityEngine; using UnityEditor; public class 源生自定义菜单 { [InitializeOnLoadMethod] static void InitializeOnLoadMethod() { SceneView.onSceneGUIDelegate = delegate (SceneView sceneView) { Event e = Event.current; //鼠标右键抬起时 if (e != null && e.button == 1 && e.type == EventType.MouseUp) { Vector2 mousePosition = e.mousePosition; //设置菜单项 var options = new GUIContent[] { new GUIContent("Test1"), new GUIContent("Test2"), new GUIContent(""), new GUIContent("Test/Test3"), new GUIContent("Test/Test4") }; //设置菜单显示区域 var selected = -1; var userData = Selection.activeGameObject; var width = 100; var height = 100; var position = new Rect(mousePosition.x, mousePosition.y - height, width, height); //显示菜单 EditorUtility.DisplayCustomMenu(position, options, selected, delegate (object data, string[] opt, int select) { Debug.Log(opt[select]); }, userData ); e.Use(); } }; } }
在上述代码中,首先监听鼠标右键以及获取鼠标位置,接着使用EditorUtility.DisplayCustomMenu()方法弹出自定义菜单,以及监听菜单选择后的事件。
效果如下所示: