包含此页的版本:
不含此页的版本:
版本: 2021.3+
此示例演示如何使用binding-path属性,以将字段绑定到 SerializedObject 的嵌套属性。
此示例创建自定义检查器一个 Unity 窗口,显示有关当前选定游戏对象、资产或项目设置的信息,允许您检查和编辑值。更多信息
请参阅术语表UI 包含以下内容:
您可以在此 GitHub 存储库中找到此示例创建的已完成文件。
本指南适用于熟悉 Unity 编辑器、UI 工具包和 C# 脚本的开发人员。在开始之前,请熟悉以下内容:
BindableElementPropertyField创建一个 C# 脚本,为坦克定义一个类,该类具有生命值,使其可破坏。
使用任何模板在 Unity 中创建项目。
在您的项目窗口一个窗口,显示您的内容Assets文件夹(项目选项卡)更多信息
在术语表中查看,创建一个名为bind-nested-properties以存储所有文件。
创建名为DestructibleTankScript.cs并将其内容替换为以下内容:
using System;
using UnityEngine;
using UnityEngine.Serialization;
[Serializable]
public struct Health
{
public int armor;
public int life;
}
[ExecuteInEditMode]
public class DestructibleTankScript : MonoBehaviour
{
public string tankName = "Tank";
public float tankSize = 1;
public Health health;
private void Update()
{
gameObject.name = tankName;
gameObject.transform.localScale = new Vector3(tankSize, tankSize, tankSize);
}
public void Reset()
{
health.armor = 100;
health.life = 10;
}
}
使用 BindableElement 创建 UXML 文件。设置 BindableElement 的binding-path到health属性并设置每个子元素的binding-path的 BindableElement 添加到armor和life属性health.
在 bind-nested-properties 文件夹中,创建一个名为Editor.
在 Editor 文件夹中,创建一个名为tank_inspector_styles.uss并将其内容替换为以下内容:
.container {
background-color: rgb(80, 80, 80);
flex-direction: column;
}
Label {
background-color: rgb(80, 80, 80);
}
TextField:hover {
background-color: rgb(255, 255, 0);
}
FloatField {
background-color: rgb(0, 0, 255);
}
创建名为destructible_tank_editor.uxml并将其内容替换为以下内容:
<UXML xmlns="UnityEngine.UIElements" xmlns:ue="UnityEditor.UIElements">
<Style src="tank_inspector_styles.uss"/>
<VisualElement name="row" class="container">
<Label text="Tank Script - Custom Inspector" />
<ue:PropertyField binding-path="tankName" name="tank-name-field" />
<ue:PropertyField binding-path="tankSize" name="tank-size-field" />
<BindableElement binding-path="health">
<ue:PropertyField binding-path="armor"/>
<ue:PropertyField binding-path="life"/>
</BindableElement>
</VisualElement>
</UXML>
创建一个 C# 脚本,用于为DestructibleTankScript.
创建名为DestructibleTankEditor.cs并将其内容替换为以下内容:
using UnityEditor;
using UnityEngine;
using UnityEngine.UIElements;
[CustomEditor(typeof(DestructibleTankScript))]
public class DestructibleTankEditor : Editor
{
[SerializeField]
VisualTreeAsset visualTreeAsset;
public override VisualElement CreateInspectorGUI()
{
return visualTreeAsset.CloneTree();
}
}
选择DestructibleTankEditor.cs在“项目”窗口中。
拉destructible_tank_editor.uxml到检查器中的可视化树资产。
health.armor和health.life性能。如果更改检查器中的值,则基础属性的值会更改。