Version: Unity 6.0 (6000.0)
言語 : 日本語
カメラオーバーレイ
シーンビューのグリッドスナップ

独自のオーバーレイの作成

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

ヒント: UIElement の作成については、開発者向けの UI 要素ガイドを参照してください。

EditorToolbarElement を理解する

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

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

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

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

ヒント:ツールバーが水平または垂直にドッキングされている場合、テキストが表示されないか、クリッピングされる場合があります。各ツールバーにアイコンを指定して、テキストのクリッピングを回避できます。

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

すべてのオーバーレイは、オーバーレイ基本クラスから継承して CreatePanelContent メソッドを実装する必要があります。これによって基本パネルが作成され、使用やツールバー要素の追加が可能になります。

パネルオーバーレイを作成するには、以下を行います。

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

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

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

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

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

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

  7. OverlayAttribute で、オーバーレイを表示するウィンドウの種類を指定します。

    • オーバーレイをすべての Editor ウィンドウで使用できるようにするには、タイプに 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 を渡すパラメーターなしのコンストラクターを実装します。パネルオーバーレイとは異なり、コンテンツは収集されて一連の要素のまとまりを形成する独立した部分として定義されます。

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

  • EditorToolbarElement(Identifier, EditorWindowType) を使用して、ToolbarOverlay の実装で使用するツールバー要素を登録します。
  • すべてのオーバーレイに 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.

}
}

要素の 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";
        }
    }
}

要素の 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();
    }
}

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

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

}

EditorToolbarDropdownToggle

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

[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();
    }
}

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

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


}
カメラオーバーレイ
シーンビューのグリッドスナップ