1. 程式人生 > >拓展編輯器(十八)_源生自定義選單

拓展編輯器(十八)_源生自定義選單

  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()方法彈出自定義選單,以及監聽選單選擇後的事件。

效果如下所示: