Version: 6000.3
语言: 中文
自定义自定义控件UXML标签名称
为复杂数据类型定义自定义控件属性

定义内置类型的 UXML 属性

要为自定义控件定义 UXML 属性,请将UxmlAttribute属性添加到要在 UXML 和 UI Builder 中公开的属性。

UxmlAttribute将字段或属性链接到 UXML 属性。Unity 会根据需要自动处理值与 UXML 属性字符串的转换。Unity 为常见类型提供了一组内置转换器,例如int,float,bool,stringVector2.

默认情况下,UI Toolkit 将 C# 驼峰命名法或帕斯卡大小写属性名称解析为用连字符连接的小写单词。例如,名为MyFloatmyFloat在 C# 中变成my-float在UXML和UI Builder中。你还可以自定义UXL属性名称

以下示例创建具有多个自定义属性的自定义控件:

using System;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UIElements;

[UxmlElement]
public partial class ExampleVisualElement : VisualElement
{
    [UxmlAttribute]
    public string myStringValue { get; set; }

    [UxmlAttribute]
    public int myIntValue { get; set; }

    [UxmlAttribute]
    public float myFloatValue { get; set; }

    [UxmlAttribute]
    public List<int> myListOfInts { get; set; }

    [UxmlAttribute, UxmlTypeReference(typeof(VisualElement))]
    public Type myType { get; set; }

    [UxmlAttribute]
    public Texture2D myTexture { get; set; }

    [UxmlAttribute]
    public Color myColor { get; set; }
}

以下示例 UXML 文档使用自定义控件:

<ui:UXML xmlns:ui="UnityEngine.UIElements">
    <ExampleElement my-string-value="Hello World" my-int-value="123" />
    <ExampleElement my-float-value="3.14" my-list-of-ints="1,2,3" />
    <ExampleElement my-string-value="Hello World" my-int-value="123" />
    <ExampleElement my-texture="project://database/Assets/MyTexture.png" />
    <ExampleElement my-color="#FF0000FF" />
    <ExampleElement my-type="UnityEngine.UIElements.Button, UnityEngine.UIElementsModule" />
</ui:UXML>

其他资源

自定义自定义控件UXML标签名称
为复杂数据类型定义自定义控件属性