Unity3D:创建自定义叠加

推荐:将NSDT场景编辑器加入你的3D工具链
3D工具集:NSDT简石数字孪生

创建自定义叠加

您可以为场景视图窗口创建自定义面板叠加和工具栏叠加。

  • 面板叠加
  • 工具栏叠加

提示:有关创建 UIE 的信息,请参阅 UI 元素开发人员指南。

编辑器工具栏元素

工具栏元素可以包含文本、图标或两者的组合。

使用 [] 注册要在实现中使用的工具栏元素。EditorToolbarElement(Identifier, EditorWindowType)ToolbarOverlay

您可以继承任何 VisualElement 类型并自行提供样式,但工具栏元素需要特定的样式,因此最好继承预定义类型之一:EditorToolbar

  • 编辑器工具栏按钮 - 基于UnityEditor.UIElements.ToolbarButton
  • 编辑器工具栏下拉列表 - 基于EditorToolbarButton
  • 编辑器工具栏下拉切换 - 基于UnityEngine.UIElements.BaseField<bool>
  • 编辑器工具栏切换 - 基于UnityEditor.UIElements.ToolbarToggle

提示:如果工具栏水平或垂直停靠,则文本将被剪裁或不可见,因此请为每个工具栏指定一个图标。

面板叠加

所有 Overlay 都必须继承 Overlay 基类并实现 CreatePanelContent() 方法。这将创建一个基本面板,您可以按原样使用该面板或添加工具栏元素。

  1. 在编辑器文件夹中创建一个新的 C# 脚本并命名它。
  2. 打开新脚本。
  3. 删除主大括号之间的样板内容,并在命名空间中实现类。OverlayUnityEditor.Overlays
  4. 重写函数并将内容添加到可视元素。CreatePanelContent
  5. 将属性添加到类中,并指定此覆盖将在哪种类型的窗口中可用。 指定为类型将使叠加在所有编辑器窗口中可用,指定将使叠加仅在场景视图中可用。OverlayEditorWindowSceneView
  6. 添加名称、ID 和显示名称。
  7. 可选:将属性添加到类以指定在精简模式下使用的图标。如果未指定图标,则默认情况下,系统使用覆盖名称的前两个字母(或前两个单词的前两个首字母)。IconOverlay

示例

using UnityEditor;
using UnityEditor.Overlays;
using UnityEngine.UIElements;
[Overlay(typeof(SceneView), "My Custom Toolbar", 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。与面板叠加不同,内容被定义为收集以形成元素条带的独立片段。

  1. 与面板覆盖一样,首先创建一个 C# 脚本并将其保存在编辑器文件夹中,然后打开并编辑脚本。
  2. 添加工具栏元素。
  3. 将工具栏元素添加到覆盖构造函数。
  4. 添加面板叠加并使用工具栏元素实现。

创建工具栏叠加时:

  • 用于注册要在实现中使用的工具栏元素。[EditorToolbarElement(Identifier, EditorWindowType)]ToolbarOverlay
  • 所有叠加都必须使用OverlayAttribute
  • 工具栏覆盖必须继承和实现无参数构造函数。ToolbarOverlay
  • 工具栏的内容填充字符串 ID,这些 ID 将传递给基构造函数。
  • ID 由 定义。EditorToolbarElementAttribute
  • Icon属性定义折叠叠加时可见的图标。如果未提供,则使用覆盖名称的前两个字母(或前两个单词的前两个首字母)。

在叠加中实现特定于工具栏覆盖的元素时:

  • IAccessContainerWindow 接口仅用于工具栏,因此,元素不会知道其上下文。在下拉列表切换示例中,切换元素不会执行任何操作。
  • 工具栏元素不会在叠加层中承载其样式。对视觉对象使用 UIElement 样式。

示例

此示例演示名为“元素工具栏示例”的覆盖,该示例演示工具栏元素

  • 编辑器工具栏按钮
  • 编辑器工具栏切换
  • 编辑器工具栏下拉列表
  • 编辑器工具栏下拉切换

每个工具栏元素都作为独立类创建,然后添加到“覆盖”面板中。

  • 它可以作为面板、水平和垂直排列。
  • 这些按钮包括文本和工具提示。
  • 工具栏具有由属性定义的图标,当工具栏折叠时,这些图标将可见。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 中的等效控件相同,但继承了一些工具栏功能(如折叠状态、方向和面板)和特定样式。

编辑器工具栏按钮

一个独立的类,将包含元素的所有逻辑。下面是一个按钮示例,该按钮在单击时创建多维数据集。

[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) { }

}

编辑器工具栏切换

创建一个包含元素的所有逻辑的独立类。下面是一个切换的简单示例,该切换开关在控制台中打印其状态并在元素中更新其文本。

[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
) { }

}

编辑器工具栏下拉列表

创建一个包含元素的所有逻辑的独立类。下面是一个下拉列表的简单示例,该下拉列表使用下拉选择调整其文本。

[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
) { }

}

编辑器工具栏下拉切换

创建一个包含元素的所有逻辑的独立类。下拉切换是也可以切换的下拉列表(如场景视图中的小控件菜单)。本示例在 Scene 视图的一角创建一个彩色矩形,当它切换时,该矩形与下拉列表中选择的颜色进行了切换。

[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
) { }


}

面板叠加

实现面板覆盖并添加工具栏元素独立类。在下面的示例中,包含所有工具栏元素以演示如何向工具栏添加多个元素。工具栏元素必须包含在面板叠加中才能显示。

[Overlay(typeof(SceneView), "ElementToolbar Example")]
[Icon("Assets/unity.png")]
public class EditorToolbarExample : Overlay
{
    public override VisualElement CreatePanelContent()
    {
        var root = new VisualElement() { name = "My Tool Root" };
        root.Add(new CreateCube());
        root.Add(new ToggleExample());
        root.Add(new DropdownExample());
        root.Add(new DropdownToggleExample());
        return root;
    }
}

此文由3D建模学习工作室整理翻译,转载请注明出处!

上一篇:Unity3D:Pick and select GameObjects (mvrlink.com)

下一篇:Unity3D:网格对齐 (mvrlink.com)

NSDT场景编辑器 | NSDT 数字孪生 | GLTF在线编辑器 | 3D模型在线转换 | UnrealSynth虚幻合成数据生成器 | 3D模型自动纹理化工具
2023 power by nsdt©鄂ICP备2023000829号