UXML 格式 - Unity 手册 (unity3d.com)
创建自定义VisualElement的类StatusBar,并继承自VisualElement。
using UnityEditor;
using UnityEngine.UIElements;
public class StatusBar : VisualElement
{
private Label _descriptionLabel = default;
public string Discription
{
get => _descriptionLabel.text;
set => _descriptionLabel.text = value;
}
//..............................
//这里是uxml的路径
private const string UXML_PATH = "Assets/Editor/StatusBar.uxml";
public StatusBar()
{
VisualTreeAsset template = AssetDatabase.LoadAssetAtPath<VisualTreeAsset>(UXML_PATH);
template.CloneTree(this);
Init();
}
public void Init()
{
//设置好Label变量
_descriptionLabel = this.Q<Label>("description");
}
//
public new class UxmlFactory : UxmlFactory<StatusBar, Traits> {}
public class Traits : UxmlTraits
{
//绑定所需的Uxml属性
readonly UxmlStringAttributeDescription _description
= new UxmlStringAttributeDescription {name = "showText"};
public override void Init(VisualElement ve, IUxmlAttributes bag, CreationContext cc)
{
base.Init(ve, bag, cc);
StatusBar statusBar = ve as StatusBar;
statusBar.Discription = _description.GetValueFromBag(bag, cc);
}
}
}
Statusbar的UXML文件定义如下。
<?xml version="1.0" encoding="utf-8"?>
<UXML
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="UnityEngine.UIElements"
xsi:noNamespaceSchemaLocation="../UIElementsSchema/UIElements.xsd"
xsi:schemaLocation="UnityEngine.UIElements ../UIElementsSchema/UnityEngine.UIElements.xsd">
<Label name="description" text="helloWorld"/>
</UXML>
这里设置Label实际上是对StatusBar中的定义:
private Label _descriptionLabel = default;
使用这个自定义的VisualElement的TestWindow的UXML定义如下。
<ui:UXML xmlns:ui="UnityEngine.UIElements" xmlns:uie="UnityEditor.UIElements">
<StatusBar showText="Test"/>
</ui:UXML>
在最后显示时看到显示的Label上的文本是Test,说明TestWindow.uxml中的定义会覆盖原本引用的StatusBar.uxml中的定义。
|