【Unity】エディタ拡張で右クリックメニューを追加する

f:id:halya_11:20180308114257p:plain

エディタ拡張で右クリックメニューを追加する方法です。

ソースコード

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
#if UNITY_EDITOR
using UnityEditor;
#endif

public class RightClickMenu : MonoBehaviour {

    [SerializeField]
    private int _sampleInt;
}

#if UNITY_EDITOR
[CustomEditor(typeof(RightClickMenu))]
public class RightClickMenuEditor: Editor
{
    private RightClickMenu _target = null;

    public override void OnInspectorGUI()
    {
        base.OnInspectorGUI();
        var rect = GUILayoutUtility.GetLastRect();
        RightClickMenu(rect);
    }

    static void RightClickMenu (Rect rect)
    {
        GUI.enabled = true;
        if (rect.Contains (Event.current.mousePosition) && Event.current.type == EventType.MouseDown && Event.current.button == 1)
        {
            GenericMenu menu = new GenericMenu();
            var enabled = true;
            menu.AddItem(new GUIContent ("メニュー名1"), enabled, () => { Debug.Log("クリック時の処理1"); });
            menu.AddItem(new GUIContent ("メニュー名2"), enabled, () => { Debug.Log("クリック時の処理2"); });
            menu.AddItem(new GUIContent ("メニュー名3"), enabled, () => { Debug.Log("クリック時の処理3"); });
            menu.ShowAsContext();
        }
    }
}
#endif

結果

f:id:halya_11:20180308114257p:plain