Version: 6000.3
语言: 中文
使用 ListView 绑定到列表
绑定自定义控件

绑定到没有 ListView 的列表

版本: 2023.2+

可以在没有 ListView 的情况下绑定到列表。为此,请将每个元素绑定到序列化对象的数组中的项,并跟踪数组大小的值。在某些情况下,数组大小可能会更改,例如撤消或重置作。

此示例演示如何在没有 ListView 的情况下绑定到列表。

示例概述

此示例创建 TexturePreviewElements 列表,并将该列表绑定到 Texture2D 对象的基础列表。

不使用 ListView 的纹理列表,显示在 Unity 编辑器中。
不使用 ListView 的纹理列表,显示在 Unity 编辑器中。

您可以在此 GitHub 存储库中找到此示例创建的已完成文件。

先决条件

本指南适用于熟悉 Unity 编辑器、UI 工具包和 C# 脚本的开发人员。在开始之前,请熟悉以下内容:

创建包含列表的对象

创建包含列表的 C# 类。此列表是绑定的目标。

  1. 使用任何模板在 Unity 中创建项目。
  2. 在您的项目窗口一个窗口,显示您的内容Assets文件夹(项目选项卡)更多信息
    术语表中查看
    ,创建一个名为bind-to-list-without-ListView以存储您的所有文件。
  3. 创建名为TexturePackAsset.cs并将其内容替换为以下内容:
using System.Collections.Generic;
using UnityEngine;

namespace UIToolkitExamples
{
    [CreateAssetMenu(menuName = "UIToolkitExamples/TexturePackAsset")]
    public class TexturePackAsset : ScriptableObject
    {
        public List<Texture2D> textures;

        public void Reset()
        {
            textures = new() { null, null, null, null };
        }
    }
}

创建自定义控件并设置其样式

使用 C# 创建表示对 2D 纹理资产的引用的自定义控件,并使用 USS 设置其样式。

  1. 在该文件夹中,创建一个名为Editor.
  2. Editor 文件夹中,创建一个名为TexturePreviewElement.cs.
  3. 替换TexturePreviewElement.cs替换为以下内容:
using System;
using UnityEditor.UIElements;
using UnityEngine;
using UnityEngine.UIElements;
using Object = UnityEngine.Object;

namespace UIToolkitExamples
{
    [UxmlElement]
    public partial class TexturePreviewElement : BindableElement, INotifyValueChanged<Object>
    {
        public static readonly string ussClassName = "texture-preview-element";

        Image m_Preview;
        ObjectField m_ObjectField;
        Texture2D m_Value;

        public TexturePreviewElement()
        {
            AddToClassList(ussClassName);

            // Create a preview image.
            m_Preview = new Image();
            Add(m_Preview);

            // Create an ObjectField, set its object type, and register a callback when its value changes.
            m_ObjectField = new ObjectField();
            m_ObjectField.objectType = typeof(Texture2D);
            m_ObjectField.RegisterValueChangedCallback(OnObjectFieldValueChanged);
            Add(m_ObjectField);

            styleSheets.Add(Resources.Load<StyleSheet>("texture_preview_element"));
        }
        
        void OnObjectFieldValueChanged(ChangeEvent<Object> evt)
        {
            value = evt.newValue;
        }

        public void SetValueWithoutNotify(Object newValue)
        {
            if (newValue == null || newValue is Texture2D)
            {
                // Update the preview Image and update the ObjectField.
                m_Value = newValue as Texture2D;
                m_Preview.image = m_Value;
                // Notice that this line calls the ObjectField's SetValueWithoutNotify() method instead of just setting
                // m_ObjectField.value. This is very important; you don't want m_ObjectField to send a ChangeEvent.
                m_ObjectField.SetValueWithoutNotify(m_Value);
            }
            else throw new ArgumentException($"Expected object of type {typeof(Texture2D)}");
        }

        public Object value
        {
            get => m_Value;
            // The setter is called when the user changes the value of the ObjectField, which calls
            // OnObjectFieldValueChanged(), which calls this.
            set
            {
                if (value == this.value)
                    return;

                var previous = this.value;
                SetValueWithoutNotify(value);

                using (var evt = ChangeEvent<Object>.GetPooled(previous, value))
                {
                    evt.target = this;
                    SendEvent(evt);
                }
            }
        }
    }
}
  1. Editor 文件夹中,创建一个名为Resources.
  2. “资源”文件夹中,创建一个名为texture_preview_element.uss并将其内容替换为以下内容:
.texture-preview-element {
    width: 200px;
    height: 200px;
}

.texture-preview-element > .unity-image {
    flex-grow: 1;
}

创建自定义编辑器并设置绑定

使用创建资产的 C# 脚本创建自定义编辑器。

要更改纹理列表的大小,当TexturePreviewElements在 UI 更改中,调用SetupList()方法,并遍历序列化列表中的条目列表。

绑定每个TexturePreviewElement到纹理列表,调用BindProperty()属性名称为TexturePackAsset.textures.

  1. Editor 文件夹中,创建一个名为TexturePackEditor.cs并将其内容替换为以下内容:
using UnityEditor;
using UnityEditor.UIElements;
using UnityEngine;
using UnityEngine.UIElements;

namespace UIToolkitExamples
{
    [CustomEditor(typeof(TexturePackAsset))]
    public class TexturePackEditor : Editor
    {
        [SerializeField]
        VisualTreeAsset m_VisualTreeAsset;

        public override VisualElement CreateInspectorGUI()
        {
            var editor = m_VisualTreeAsset.CloneTree();

            var container = editor.Q(className: "preview-container");

            SetupList(container);

            // Watch the array size to handle the list being changed        
            var propertyForSize = serializedObject.FindProperty(nameof(TexturePackAsset.textures) + ".Array");
            propertyForSize.Next(true); // Expand to obtain array size
            editor.TrackPropertyValue(propertyForSize, prop => SetupList(container));

            editor.Q<Button>("add-button").RegisterCallback<ClickEvent>(OnClick);

            return editor;
        }

        void SetupList(VisualElement container)
        {
            var property = serializedObject.FindProperty(nameof(TexturePackAsset.textures) + ".Array");

            var endProperty = property.GetEndProperty();

            property.NextVisible(true); // Expand the first child.

            var childIndex = 0;

            // Iterate each property under the array and populate the container with preview elements
            do
            {
                // Stop if we've reached the end of the array
                if (SerializedProperty.EqualContents(property, endProperty))
                    break;

                // Skip the array size property
                if (property.propertyType == SerializedPropertyType.ArraySize)
                    continue;

                TexturePreviewElement element;

                // Find an existing element or create one
                if (childIndex < container.childCount)
                {
                    element = (TexturePreviewElement)container[childIndex];
                }
                else
                {
                    element = new TexturePreviewElement();
                    container.Add(element);
                }

                element.BindProperty(property);

                ++childIndex;
            }
            while (property.NextVisible(false));   // Never expand children.

            // Remove excess elements if the array is now smaller
            while (childIndex < container.childCount)
            {
                container.RemoveAt(container.childCount - 1);
            }
        }

        void OnClick(ClickEvent evt)
        {
            var property = serializedObject.FindProperty(nameof(TexturePackAsset.textures));
            property.arraySize += 1;
            serializedObject.ApplyModifiedProperties();
        }
    }
}
  1. 创建一个名为texture_pack_editor.uxml并将其内容替换为以下内容:
<ui:UXML xmlns:ui="UnityEngine.UIElements" xmlns:uie="UnityEditor.UIElements" xmlns="UnityEngine.UIElements" example="UIToolkitExamples" editor-extension-mode="True">
    <ui:ScrollView>
        <ui:VisualElement class="preview-container" style="flex-wrap: wrap; flex-direction: row; justify-content: space-around;" />
    </ui:ScrollView>
    <ui:Button name="add-button" text="Add" />
</ui:UXML>
  1. 在“项目”窗口中,选择TexturePackEditor.cs
  2. texture_pack_editor.uxml 拖到 Visual Tree Asset 中的检查器一个 Unity 窗口,显示有关当前选定游戏对象、资产或项目设置的信息,允许您检查和编辑值。更多信息
    请参阅术语表
    .

测试绑定

  1. 从菜单中,选择 资产(Assets) > 创建(Create) > UIToolkitExamples > TexturePackAsset。这将创建一个名为 新建纹理包资产(New Texture Pack Asset) 的资产。
  2. 在 项目(Project) 窗口中,选择 新建纹理包资产(New Texture Pack Asset) 。这将在检查器中显示四个 TexturePreviewElement 元素。
  3. 将 2D 图像资源分配给这些元素,或使用“添加”按钮添加新元素。如果您在 Inspector UI 中进行更改,则TexturePackAsset.textures对象更改。

提示:要导入一些纹理并将它们分配给列表中的不同条目,请尝试这个免费的 Playground 资源商店插件

其他资源

使用 ListView 绑定到列表
绑定自定义控件