ゲーム開発Unityエディター拡張ナレッジシリーズ:エディターウィンドウをカスタマイズし、右クリックしてカスタムメニューバーを表示します

参照:

        https://docs.unity3d.com/ScriptReference/GenericMenu.html

        https://docs.unity3d.com/ScriptReference/Event-button.html

 

効果:

using UnityEngine;
using UnityEditor;

public class MenuItemForCustomizedWindow : EditorWindow
{
    [MenuItem("MenuItemForCustomizedWindow")]
    static void Init()
    {
        EditorWindow window = GetWindow<MenuItemForCustomizedWindow>();
        window.Show();
    }

    // serialize field on window so its value will be saved when Unity recompiles
    [SerializeField]
    Color m_Color = Color.white;

    void OnEnable()
    {
        titleContent = new GUIContent("GUI Color");
    }

    // a method to simplify adding menu items
    void AddMenuItemForColor(GenericMenu menu, string menuPath, Color color)
    {
        // the menu item is marked as selected if it matches the current value of m_Color
        menu.AddItem(new GUIContent(menuPath), m_Color.Equals(color), OnColorSelected, color);
    }

    // the GenericMenu.MenuFunction2 event handler for when a menu item is selected
    void OnColorSelected(object color)
    {
        m_Color = (Color)color;
    }

    void OnGUI()
    {
        // set the GUI to use the color stored in m_Color
        GUI.color = m_Color;
        GUILayout.Button("Showed Button");

        EditorGUILayout.LabelField("鼠标在窗口的位置", Event.current.mousePosition.ToString());

        if (EditorWindow.focusedWindow == this && Event.current.button == 1 && Event.current.type == EventType.MouseDown)
        {
            // create the menu and add items to it
            GenericMenu menu = new GenericMenu();

            // forward slashes nest menu items under submenus
            AddMenuItemForColor(menu, "RGB/Red", Color.red);
            AddMenuItemForColor(menu, "RGB/Green", Color.green);
            AddMenuItemForColor(menu, "RGB/Blue", Color.blue);

            // an empty string will create a separator at the top level
            menu.AddSeparator("");

            AddMenuItemForColor(menu, "CMYK/Cyan", Color.cyan);
            AddMenuItemForColor(menu, "CMYK/Yellow", Color.yellow);
            AddMenuItemForColor(menu, "CMYK/Magenta", Color.magenta);
            // a trailing slash will nest a separator in a submenu
            menu.AddSeparator("CMYK/");
            AddMenuItemForColor(menu, "CMYK/Black", Color.black);

            menu.AddSeparator("");

            AddMenuItemForColor(menu, "White", Color.white);

            // display the menu
            menu.ShowAsContext();
        }
    }
}

おすすめ

転載: blog.csdn.net/qq1090504117/article/details/111592481
おすすめ