包含此页的版本:
不含此页的版本:
Unity 6 引入了一些改进,可简化自定义控件的创建。本指南介绍如何将自定义控件从以前的版本迁移到 Unity 6 改进的工作流程。
以前,创建自定义控件需要使用UxmlTraits类来定义属性。以下示例演示了ProgressBar控制。
这些示例侧重于属性创作,不包括控件的行为。它创建了一个UxmlTraits类,该类定义了ProgressBar控制。对于每个属性,该类指定以下内容:
然后,它获取每个属性的值并将其分配给元素。它还添加了一个UxmlFactory创建元素实例的类。
using UnityEngine.UIElements;
public class ProgressBar : VisualElement
{
public new class UxmlFactory : UxmlFactory<ProgressBar, UxmlTraits> { }
public new class UxmlTraits : BindableElement.UxmlTraits
{
UxmlFloatAttributeDescription m_LowValue = new UxmlFloatAttributeDescription { name = "low-value", defaultValue = 0 };
UxmlFloatAttributeDescription m_HighValue = new UxmlFloatAttributeDescription { name = "high-value", defaultValue = 100 };
UxmlFloatAttributeDescription m_Value = new UxmlFloatAttributeDescription { name = "value", defaultValue = 0 };
UxmlStringAttributeDescription m_Title = new UxmlStringAttributeDescription() { name = "title", defaultValue = string.Empty };
public override void Init(VisualElement ve, IUxmlAttributes bag, CreationContext cc)
{
base.Init(ve, bag, cc);
var bar = ve as ProgressBar;
bar.lowValue = m_LowValue.GetValueFromBag(bag, cc);
bar.highValue = m_HighValue.GetValueFromBag(bag, cc);
bar.value = m_Value.GetValueFromBag(bag, cc);
bar.title = m_Title.GetValueFromBag(bag, cc);
}
}
public string title { get; set; }
public float lowValue { get; set; }
public float highValue { get; set; }
public float value { get; set; }
}
Unity 6 通过UxmlElement和UxmlAttribute属性,无需UxmlTraits和UxmlFactory.新系统通过自动处理与UXML属性字符串之间的值转换来简化流程。
下面显示了更新的ProgressBar例:
using UnityEngine.UIElements;
[UxmlElement]
public partial class ProgressBar : VisualElement
{
[UxmlAttribute]
public string title { get; set; }
[UxmlAttribute]
public float lowValue { get; set; }
[UxmlAttribute]
public float highValue { get; set; } = 100;
[UxmlAttribute]
public float value { get; set; }
}
以下是主要变化:
两个系统的 UXML 用法保持不变:
<ui:UXML xmlns:ui="UnityEngine.UIElements">
<ProgressBar title="My Progress bar" low-value="0" high-value="1" value="0.5" />
</ui:UXML>
如果元素缺少UxmlElement属性,Unity 默认为UxmlTraits和UxmlFactory序列化系统。通过使用单一序列化方法来确保一致性视觉元素实例化或派生自 C# 的可视化树的节点VisualElement类。您可以设置外观样式、定义行为并将其作为 UI 的一部分显示在屏幕上。更多信息
请参阅术语表.虽然这两个系统可以在 UXML 文件中共存,但不要将它们与单个元素混合使用。
迁移到新系统后,重新导入 UXML 资源以匹配更新的代码。虽然此过程会自动发生,但需要重新构建任何包含UXML文件的先前构建的资产包才能正常运行。