【Unity】UI ToolkitでPopupWindowを構築する方法

UnityのUI ToolkitでPopupWindowを構築する方法についてまとめました。

Unity 2022.2.17

はじめに

PopupWindowクラスを使うと、UnityエディタのポップアップメニューのようなUIを作ることができます。
IMGUIでこれを作る場合には、以下の記事のようにPopupWindowContent.OnGUIGUIを構築するためのコードを書きます

light11.hatenadiary.com

これに対して、UI ToolkitでPopupWindowContentを作成する場合はOnGUIは使いません。

本記事ではこの方法についてまとめます。

PopupWindowContentを作る

UI ToolkitでPopupWindowContentを作成する場合には、OnGUIには何も書かず、PopupWindowを開いた時の処理であるOnOpenにUIを構築する処理を書きます。

using UnityEditor;
using UnityEngine;
using UnityEngine.UIElements;

public sealed class PopupContentExample : PopupWindowContent
{
    // サイズ
    public override Vector2 GetWindowSize()
    {
        return new Vector2(200, 100);
    }

    public override void OnGUI(Rect rect)
    {
        // UI Toolkitを使う場合にはOnGUIには何も書かない
    }

    // 開く時の処理
    public override void OnOpen()
    {
        // editorWindow.rootVisualElementに対してUIを追加していく
        // UXMLファイルを使う場合には、editorWindow.rootVisualElementにCloneTreeしてもOK
        var label = new Label("This is PopupContentExample");
        editorWindow.rootVisualElement.Add(label);
    }

    // 閉じる時の処理
    public override void OnClose()
    {
    }
}

作成したVisualElementeditorWindow.rootVisualElementに対して追加します。

また、コード内のコメントの通り、UXMLファイルを読み込んでCloneTreeすることでそれをルートとして使うこともできます。

PopupWindowを表示する

それでは次に前節で作ったPopupWindowContentを表示してみます。
今回は以下のように、EditorWindow上のボタンを押したらそのボタンの下に表示するようにします。

using UnityEditor;
using UnityEngine.UIElements;
using PopupWindow = UnityEditor.PopupWindow;

public sealed class Example : EditorWindow
{
    private void CreateGUI()
    {
        var button = new Button();
        button.clicked += () =>
        {
            var content = new PopupContentExample();
            PopupWindow.Show(button.worldBound, content);
        };
        button.text = "Open Popup";
        rootVisualElement.Add(button);
    }

    [MenuItem("Window/Example")]
    private static void Open()
    {
        GetWindow<Example>();
    }
}

Window > Exampleからこのウィンドウを開いて、ウィンドウに表示されているボタンを押下すると以下の結果が得られます。

結果

正常に動作していることを確認できました。

関連

light11.hatenadiary.com

参考

docs.unity3d.com