EditorWindow Custom Context Menu

weixin_34365417發表於2016-07-25

這是轉自另一篇文章 EditorWindow Custom Context Menu

Unity中的視窗都可以通過右鍵視窗的tab 或者 點選視窗右上角的一個選單按鈕 來顯示視窗選單項

1310035-16f7742a389efb9f.png
右鍵視窗tab
1310035-599a5b8ed2e3ef5d.png
視窗右上角選單按鈕

視窗都有預設的選單項。。可以通過實現 IHasCustomMenu 介面中的 AddItemsToMenu 函式 來新增自定義的選單項

程式碼:

using UnityEditor;
using UnityEngine;

public class CustomMenuEditorWindow : EditorWindow, IHasCustomMenu
{
    [MenuItem("Window/Custom Menu Window")]
    public static void OpenCustomMenuWindow()
    {
        EditorWindow window = EditorWindow.GetWindow<CustomMenuEditorWindow>();
    }

    private GUIContent m_MenuItem1 = new GUIContent("Menu Item 1");
    private GUIContent m_MenuItem2 = new GUIContent("Menu Item 2");

    private bool m_Item2On = false;


    void Awake()
    {
        titleContent = new GUIContent("Custom Menu");
    }

    //Implement IHasCustomMenu.AddItemsToMenu
    public void AddItemsToMenu(GenericMenu menu)
    {
        menu.AddItem(m_MenuItem1, false, MenuItem1Selected);
        menu.AddItem(m_MenuItem2, m_Item2On, MenuItem2Selected);

        //NOTE: do not show the menu after adding items,
        //      Unity will do that after adding the default
        //      items: maximize, close tab, add tab >
    }

    private void MenuItem1Selected()
    {
        Debug.Log("Menu Item 1 selected");
    }

    private void MenuItem2Selected()
    {
        m_Item2On = !m_Item2On;

        Debug.Log("Menu Item 2 is " + m_Item2On);
    }
}

相關文章