关于unity3d:Unity3D创建自定义叠加

63次阅读

共计 12066 个字符,预计需要花费 31 分钟才能阅读完成。

举荐:将 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)

正文完
 0