Version: 2022.3
言語: 日本語
オーバーレイ設定の作成と管理
ゲームオブジェクトの配置

カスタムオーバーレイの作成

シーンビュー のウィンドウ用に、パネルオーバーレイとツールバーオーバーレイをカスタム作成できます。

ヒント: UIElements の作成に関する詳細は、開発者向けの UI 要素ガイド を参照してください。

EditorToolbarElement について

ツールバー要素は、テキスト、アイコン、またはその両方の組み合わせを含むことができます。

ToolbarOverlay の実装に使用するツールバー要素を登録するには、EditorToolbarElement(Identifier, EditorWindowType) を使用します。

任意の VisualElement タイプを継承してスタイリングを作成できますが、ツールバー要素には特定のスタイリングが必要です。以下の定義済みの EditorToolbar タイプのうちいずれを継承することが推奨されます。

  • EditorToolbarButton: UnityEditor.UIElements.ToolbarButton に基づきます。
  • EditorToolbarToggle: UnityEditor.UIElements.ToolbarToggle に基づきます。
  • EditorToolbarDropdown: EditorToolbarButton に基づきます。
  • EditorToolbarDropdownToggle: UnityEngine.UIElements.BaseField に基づきます。

ヒント: ツールバーが水平または垂直にドッキングされている場合、そのテキストが表示されなかったり、(途中で切れて) 一部しか表示されないことがあります。テキストが切れて一部しか表示されない状態を避けるために、各ツールバーにアイコンを指定することが可能です。

パネルオーバーレイの作成

全てのオーバーレイは、Overlay 基本クラスを継承し、CreatePanelContent メソッドを実装する必要があります。これは、使用可能な基本的なパネルを作成します。このパネルにはツールバー要素を追加することができます。

パネルオーバーレイの作成は、以下の手順で行えます。

  1. Editor フォルダー 内に新しい C# スクリプト を作成します。

  2. 作成したスクリプトを開きます。

  3. スクリプトからデフォルトのコンテンツを削除します。

  4. UnityEditor.Overlays 名前空間から Overlay クラスを実装します。

  5. CreatePanelContent 関数をオーバーライドし、ビジュアル要素にコンテンツを追加します。

  6. クラスに OverlayAttribute 属性を追加します。

  7. OverlayAttribute 内で、このオーバーレイをどのタイプのウィンドウに使用するか指定します。

    • このオーバーレイを全てのエディターウィンドウで使用したい場合は、EditorWindow をタイプとして指定してください。
    • このオーバーレイをシーンビューのみで使用したい場合は、SceneView をタイプとして指定してください。
  8. OverlayAttribute 内に、オーバーレイの名前、ID、表示名を追加します。

  9. オーバーレイが折り畳まれた時に表示されるアイコンを追加するには、Overlay クラスに Icon 属性を追加し、アイコンを指定します。オーバーレイにアイコンがない場合は、システムがデフォルトで、オーバーレイの名前の最初の 2 文字または最初の 2 語の最初の 2 文字を使用します。

using UnityEditor;
using UnityEditor.Overlays;
using UnityEngine.UIElements;
[Overlay(typeof(SceneView), "Panel Overlay Example", true)]
public class MyToolButtonOverlay : Overlay
{
    public override VisualElement CreatePanelContent()
    {
        var root = new VisualElement() { name = "My Toolbar Root" };
        root.Add(new Label() { text = "Hello" });
        return root;

    }
}

ツールバーオーバーレイの作成

ツールバーオーバーレイは、ツールバー要素を格納するコンテナで、EditorToolbarElement のコレクションによって構成されます。

ツールバーオーバーレイには、ビルトインの、水平レイアウト、垂直レイアウト、パネルレイアウトがあります。ToolbarOverlay は、EditorToolbarElementAttribute ID を渡すパラメーターなしのコンストラクターを実装します。パネルオーバーレイとは異なり、コンテンツが、収集されて一連の要素のまとまりを形成する独立した部分部分として定義されます。

ツールバーオーバーレイを作成するにあたっては、以下に注意してください。

  • ToolbarOverlay の実装に使用するツールバー要素を登録するには、EditorToolbarElement(Identifier, EditorWindowType) を使用します。
  • 全てのオーバーレイに OverlayAttribute でタグ付けします。
  • ツールバーのオーバーレイが ToolbarOverlay を継承し、パラメーターなしのコンストラクターを実装していることを確認してください。
  • ツールバーのコンテンツに、ベースコンストラクターに渡される文字列 ID が追加されていることを確認してください。
  • ID が EditorToolbarElementAttribute で定義されていることを確認してください。
  • オーバーレイへのアイコンの追加は Icon 属性を使用して行います。アイコンは、オーバーレイが折り畳まれた時に表示されます。オーバーレイにアイコンがない場合は、オーバーレイの名前の最初の 2 文字 (または最初の 2 語の最初の 2 文字) が、オーバーレイが折り畳まれた時に表示されます。

オーバーレイに ToolbarOverlay 専用の要素を実装する場合は、以下に注意してください。

  • IAccessContainerWindow インターフェイスは ツールバーのみに使用します。要素はそのコンテキストを認識しません。DropdownToggleExample 内では、要素をトグルしても何も行われません。
  • ビジュアルには UIElement のスタイリングを使用します。ツールバー要素はオーバーレイ内でスタイリングを持ちません。

ツールバーオーバーレイの作成は、以下の手順で行えます。

  1. Editor フォルダー 内に新しい C# スクリプト を作成します。
  2. 作成したスクリプトを開きます。
  3. スクリプトからデフォルトのコンテンツを削除します。
  4. スクリプトにツールバー要素を追加します。
  5. ツールバー要素をオーバーレイのコンストラクターに追加します。
  6. パネルオーバーレイを追加し、ツールバー要素を実装します。

以下は、Element Toolbars Example という名前のオーバーレイの例で、これらのツールバー要素を示したものです。

  • EditorToolbarButton
  • EditorToolbarToggle
  • EditorToolbarDropdown
  • EditorToolbarDropdownToggle

各ツールバー要素は、スタンドアロンクラスとして作成され、オーバーレイパネルに追加されます。

このオーバーレイには以下の特徴があります。

  • パネル、水平、垂直の配置が可能です。
  • テキストとツールチップを含むボタンがあります。
  • Icon 属性で定義されるツールバーアイコンがあります。このアイコンは、オーバーレイが折り畳まれた時に表示されます。
    using System.Collections;
        using System.Collections.Generic;
        using System.Text;
        using UnityEngine;
        using UnityEditor.EditorTools;
        using UnityEditor.Toolbars;
        using UnityEditor.Overlays;
        using UnityEngine.UIElements;
        using UnityEditor;

        // Use [EditorToolbarElement(Identifier, EditorWindowType)] to register toolbar elements for use in ToolbarOverlay implementation.

        [EditorToolbarElement(id, typeof(SceneView))]
        class DropdownExample : EditorToolbarDropdown
        {
            public const string id = "ExampleToolbar/Dropdown";

            static string dropChoice = null;

            public DropdownExample()
            {
                text = "Axis";
                clicked += ShowDropdown;
            }

            void ShowDropdown()
            {
                var menu = new GenericMenu();
                menu.AddItem(new GUIContent("X"), dropChoice == "X", () => { text = "X"; dropChoice = "X"; });
                menu.AddItem(new GUIContent("Y"), dropChoice == "Y", () => { text = "Y"; dropChoice = "Y"; });
                menu.AddItem(new GUIContent("Z"), dropChoice == "Z", () => { text = "Z"; dropChoice = "Z"; });
                menu.ShowAsContext();
            }
        }
        [EditorToolbarElement(id, typeof(SceneView))]
        class ToggleExample : EditorToolbarToggle
        {
            public const string id = "ExampleToolbar/Toggle";
            public ToggleExample()
            {
                text = "Toggle OFF";
                this.RegisterValueChangedCallback(Test);
            }

            void Test(ChangeEvent<bool> evt)
            {
                if (evt.newValue)
                {
                    Debug.Log("ON");
                    text = "Toggle ON";
                }
                else
                {
                    Debug.Log("OFF");
                    text = "Toggle OFF";
                }
            }
        }

        [EditorToolbarElement(id, typeof(SceneView))]
        class DropdownToggleExample : EditorToolbarDropdownToggle, IAccessContainerWindow
        {
            public const string id = "ExampleToolbar/DropdownToggle";

            // This property is specified by IAccessContainerWindow and is used to access the Overlay's EditorWindow.

            public EditorWindow containerWindow { get; set; }
            static int colorIndex = 0;
            static readonly Color[] colors = new Color[] { Color.red, Color.green, Color.cyan };
            public DropdownToggleExample()
            {
                text = "Color Bar";
                tooltip = "Display a color rectangle in the top left of the Scene view. Toggle on or off, and open the dropdown" +
                          "to change the color.";

            // When the dropdown is opened, ShowColorMenu is invoked and we can create a popup menu.

                dropdownClicked += ShowColorMenu;

            // Subscribe to the Scene view OnGUI callback so that we can draw our color swatch.

                SceneView.duringSceneGui += DrawColorSwatch;
            }

            void DrawColorSwatch(SceneView view)
            {

             // Test that this callback is for the Scene View that we're interested in, and also check if the toggle is on
            // or off (value).

                if (view != containerWindow || !value)
                {
                    return;
                }

                Handles.BeginGUI();
                GUI.color = colors[colorIndex];
                GUI.DrawTexture(new Rect(8, 8, 120, 24), Texture2D.whiteTexture);
                GUI.color = Color.white;
                Handles.EndGUI();
            }

            // When the dropdown button is clicked, this method will create a popup menu at the mouse cursor position.

            void ShowColorMenu()
            {
                var menu = new GenericMenu();
                menu.AddItem(new GUIContent("Red"), colorIndex == 0, () => colorIndex = 0);
                menu.AddItem(new GUIContent("Green"), colorIndex == 1, () => colorIndex = 1);
                menu.AddItem(new GUIContent("Blue"), colorIndex == 2, () => colorIndex = 2);
                menu.ShowAsContext();
            }
        }

        [EditorToolbarElement(id, typeof(SceneView))]
        class CreateCube : EditorToolbarButton//, IAccessContainerWindow
        {
            // This ID is used to populate toolbar elements.

            public const string id = "ExampleToolbar/Button";

            // IAccessContainerWindow provides a way for toolbar elements to access the `EditorWindow` in which they exist.
            // Here we use `containerWindow` to focus the camera on our newly instantiated objects after creation.
            //public EditorWindow containerWindow { get; set; }

            // Because this is a VisualElement, it is appropriate to place initialization logic in the constructor.
            // In this method you can also register to any additional events as required. In this example there is a tooltip, an icon, and an action.

            public CreateCube()
            {

        // A toolbar element can be either text, icon, or a combination of the two. Keep in mind that if a toolbar is
            // docked horizontally the text will be clipped, so usually it's a good idea to specify an icon.

                text = "Create Cube";
                icon = AssetDatabase.LoadAssetAtPath<Texture2D>("Assets/CreateCubeIcon.png");
                tooltip = "Instantiate a cube in the scene.";
                clicked += OnClick;
            }

            // This method will be invoked when the `Create Cube` button is clicked.

            void OnClick()
            {
                var newObj = GameObject.CreatePrimitive(PrimitiveType.Cube).transform;

            // When writing editor tools don't forget to be a good citizen and implement Undo!

                Undo.RegisterCreatedObjectUndo(newObj.gameObject, "Create Cube");

            //if (containerWindow is SceneView view)
            //    view.FrameSelected();

            }

        }

        // All Overlays must be tagged with the OverlayAttribute

        [Overlay(typeof(SceneView), "ElementToolbars Example")]

            // IconAttribute provides a way to define an icon for when an Overlay is in collapsed form. If not provided, the name initials are used.

        [Icon("Assets/unity.png")]

        // Toolbar Overlays must inherit `ToolbarOverlay` and implement a parameter-less constructor. The contents of a toolbar are populated with string IDs, which are passed to the base constructor. IDs are defined by EditorToolbarElementAttribute.

        public class EditorToolbarExample : ToolbarOverlay
        {

         // ToolbarOverlay implements a parameterless constructor, passing the EditorToolbarElementAttribute ID.
        // This is the only code required to implement a toolbar Overlay. Unlike panel Overlays, the contents are defined
        // as standalone pieces that will be collected to form a strip of elements.

            EditorToolbarExample() : base(
                CreateCube.id,
                ToggleExample.id,
                DropdownExample.id,
                DropdownToggleExample.id
                )
            { }
        }


ツールバー要素の実装

ツールバー要素の制御は、UIToolkit でこれに相当するものと同じですが、一部のツールバー機能と特定のスタイリングを継承しています。

このセクションには、以下のツールバー要素の例を掲載しています。

EditorToolbarButton

EditorToolbarButton は、要素のロジックを含んだスタンドアロンクラスです。この例は、クリックするとキューブを生成するボタンを作成します。

[EditorToolbarElement(id, typeof(SceneView))]
class CreateCube : EditorToolbarButton
{
// This ID is used to populate toolbar elements.

public const string id = "ExampleToolbar/Button";   

// Because this is a VisualElement, it is appropriate to place initialization logic in the constructor.

// In this method you can also register to any additional events as required. In this example there is a tooltip, an icon, and an action.

    public CreateCube()
       {

// A toolbar element can be either text, icon, or a combination of the two. Keep in mind that if a toolbar is docked horizontally the text will be clipped, so it's a good idea to specify an icon.

            text = "Create Cube";
            icon = AssetDatabase.LoadAssetAtPath<Texture2D>("Assets/CreateCubeIcon.png");
            tooltip = "Instantiate a cube in the scene.";
            clicked += OnClick;
}

void OnClick()
{
    var newObj = GameObject.CreatePrimitive(PrimitiveType.Cube).transform;

    // When writing editor tools, don't forget to be a good citizen and implement Undo.

    Undo.RegisterCreatedObjectUndo(newObj.gameObject, "Create Cube");

// Note: Using ObjectFactory class instead of GameObject(like in this example) will register the undo entry automatically removing the need to register manually.

}
}

Overlay コンストラクターに要素の ID を追加します。

[Overlay(typeof(SceneView), "ElementToolbar Example")]
[Icon("Assets/unity.png")]
public class EditorToolbarExample : ToolbarOverlay
{
    EditorToolbarExample() : base(CreateCube.id) { }

}

EditorToolbarToggle

要素の全てのロジックを含むスタンドアロンクラスを作成します。以下の例は、コンソールに状態を表示し、要素内でそのテキストを更新するトグルを作成します。

[EditorToolbarElement(id, typeof(SceneView))]
class ToggleExample : EditorToolbarToggle
{
    public const string id = "ExampleToolbar/Toggle";
    public ToggleExample()
    {
        text = "Toggle OFF";

    // Register the class to a callback for when the toggle’s state changes

        this.RegisterValueChangedCallback(OnStateChange);
    }

    void OnStateChange(ChangeEvent<bool> evt)
    {
        if (evt.newValue)
        {

    // Put logic for when the state is ON here

                Debug.Log("Toggle State -> ON");
        text = "Toggle ON";
        }
        else
        {

    // Put logic for when the state is OFF here

                Debug.Log("Toggle State -> OFF");
        text = "Toggle OFF";
        }
    }
}

Overlay コンストラクターに要素の ID を追加します。

[[Overlay(typeof(SceneView), "ElementToolbar Example")]
[Icon("Assets/unity.png")]
public class EditorToolbarExample : ToolbarOverlay
{
    EditorToolbarExample() : base(
ToggleExample.id
) { }

}

EditorToolbarDropdown

要素の全てのロジックを含むスタンドアロンクラスを作成します。以下は、ドロップダウンの選択に応じてテキストを調整する、簡単なドロップダウンの例です。

[EditorToolbarElement(id, typeof(SceneView))]
class DropdownExample : EditorToolbarDropdown
{
    public const string id = "ExampleToolbar/Dropdown";

    static string dropChoice = null;

    public DropdownExample()
    {
        text = "Axis";
        clicked += ShowDropdown;
    }

    void ShowDropdown()
    {

// A simple GenericMenu to populate the dropdown content

        var menu = new GenericMenu();
        menu.AddItem(new GUIContent("X"), dropChoice == "X", () => { text = "X"; dropChoice = "X"; });
        menu.AddItem(new GUIContent("Y"), dropChoice == "Y", () => { text = "Y"; dropChoice = "Y"; });
        menu.AddItem(new GUIContent("Z"), dropChoice == "Z", () => { text = "Z"; dropChoice = "Z"; });
        menu.ShowAsContext();
    }
}

Overlay コンストラクターに要素の ID を追加します。

[Overlay(typeof(SceneView), "ElementToolbar Example")]
[Icon("Assets/unity.png")]
public class EditorToolbarExample : ToolbarOverlay
{
    EditorToolbarExample() : base(
DropdownExample.id
) { }

}

EditorToolbarDropdownToggle

要素の全てのロジックを含むスタンドアロンクラスを作成します。ドロップダウントグルとは、シーンビューのギズモメニューのようにトグルできるドロップダウンです。以下の例は、シーンビューの角に、オーバーレイのドロップダウンから色を選択できる長方形を作成します。

[EditorToolbarElement(id, typeof(SceneView))]
class DropdownToggleExample : EditorToolbarDropdownToggle, IAccessContainerWindow
{
    public const string id = "ExampleToolbar/DropdownToggle";


    // This property is specified by IAccessContainerWindow and is used to access the Overlay's EditorWindow.

    public EditorWindow containerWindow { get; set; }
    static int colorIndex = 0;
    static readonly Color[] colors = new Color[] { Color.red, Color.green, Color.cyan };
    public DropdownToggleExample()
    {
        text = "Color Bar";
        tooltip = "Display a color rectangle in the top left of the Scene view. Toggle on or off, and open the dropdown" +
                "to change the color.";


   // When the dropdown is opened, ShowColorMenu is invoked and you can create a pop-up menu.

        dropdownClicked += ShowColorMenu;


    // Subscribe to the Scene view OnGUI callback to draw a color swatch.

        SceneView.duringSceneGui += DrawColorSwatch;
    }


    void DrawColorSwatch(SceneView view)
    {

        // Test that this callback is for the correct Scene view, and check if the toggle is on
     // or off (value).

        if (view != containerWindow || !value)
        {
            return;
        }


        Handles.BeginGUI();
            GUI.color = colors[colorIndex];
        GUI.DrawTexture(new Rect(8, 8, 120, 24), Texture2D.whiteTexture);
        GUI.color = Color.white;
        Handles.EndGUI();
    }


    // When the drop-down button is clicked, this method creates a pop-up menu at the mouse cursor position.

    void ShowColorMenu()
    {
        var menu = new GenericMenu();
        menu.AddItem(new GUIContent("Red"), colorIndex == 0, () => colorIndex = 0);
        menu.AddItem(new GUIContent("Green"), colorIndex == 1, () => colorIndex = 1);
        menu.AddItem(new GUIContent("Blue"), colorIndex == 2, () => colorIndex = 2);
        menu.ShowAsContext();
    }
}

Overlay コンストラクターに要素の ID を追加します。

[Overlay(typeof(SceneView), "ElementToolbar Example")]
[Icon("Assets/unity.png")]
public class EditorToolbarExample : ToolbarOverlay
{
    EditorToolbarExample() : base(
DropdownToggleExample.id
) { }


}
オーバーレイ設定の作成と管理
ゲームオブジェクトの配置