可以通过以下步骤创建运行时__ UI__(即用户界面,User Interface)让用户能够与您的应用程序进行交互。Unity 目前支持三种 UI 系统。更多信息
See in Glossary 并将其显示在游戏视图中:
尝试以下简单的运行时 UI 示例以开始使用。该示例将在场景中添加一个标签、一个按钮、一个开关和一个文本字段。单击按钮时,控制台窗口会显示一条消息。选择开关并单击按钮时,控制台窗口会显示按钮的单击次数。在文本字段中输入文本消息时,控制台窗口将显示该消息。
本指南适用于熟悉 Unity 编辑器、UI 工具包和 C# 脚本的开发者。在开始之前,请熟悉以下内容:
可以在此 GitHub 代码仓库中找到此示例创建的完整文件。
创建带有标签、按钮和开关的 UI 文档。有关如何使用 UI Builder 或 UXML 添加 UI 控件的信息,请参阅 UI 工具包入门。
使用任何模板在 Unity 编辑器中创建项目。
创建名为 SimpleRuntimeUI.uxml 的 UI 文档,其中包含以下内容:
<ui:UXML xmlns:ui="UnityEngine.UIElements" xmlns:uie="UnityEditor.UIElements"
xsi="http://www.w3.org/2001/XMLSchema-instance" engine="UnityEngine.UIElements" editor="UnityEditor.UIElements"
noNamespaceSchemaLocation="../UIElementsSchema/UIElements.xsd" editor-extension-mode="False">
<ui:VisualElement style="flex-grow: 1;">
<ui:Label text="This is a Label" display-tooltip-when-elided="true"/>
<ui:Button text="This is a Button" display-tooltip-when-elided="true" name="button"/>
<ui:Toggle label="Display the counter?" name="toggle"/>
<ui:TextField picking-mode="Ignore" label="Text Field" text="filler text" name="input-message" />
</ui:VisualElement>
</ui:UXML>
在 SampleScene 中创建一个 UIDocument 游戏对象,并将 UI 文档添加为源资产。
在 SampleScene 中,选择游戏对象 (GameObject) > UI 工具包 (UI Toolkit) > UI 文档 (UI Document)。这将产生以下内容:
在层级视图中选择 UIDocument 游戏对象,然后将 SimpleRuntimeUI.uxml 从项目 (Project) 窗口拖动到检视面板 (Inspector) 窗口中 UI 文档组件的源资产 (Source Asset) 字段。这会将源资产引用到您创建的 UXML 文件。
要添加逻辑,请创建一个派生自 MonoBehaviour 的 C# 脚本来访问 UI 文档组件引用的控件。
在 UI 文档组件上调用 OnEnable 时,Unity 会加载该组件的源 UXML。为确保正确加载视觉树,请添加逻辑以与 OnEnable 方法内的控件交互。
创建名为 SimpleRuntimeUI.cs 的 C# 脚本,其中包含以下内容:
using UnityEngine;
using UnityEngine.UIElements;
public class SimpleRuntimeUI : MonoBehaviour
{
private Button _button;
private Toggle _toggle;
private int _clickCount;
//Add logic that interacts with the UI controls in the `OnEnable` methods
private void OnEnable()
{
// The UXML is already instantiated by the UIDocument component
var uiDocument = GetComponent<UIDocument>();
_button = uiDocument.rootVisualElement.Q("button") as Button;
_toggle = uiDocument.rootVisualElement.Q("toggle") as Toggle;
_button.RegisterCallback<ClickEvent>(PrintClickMessage);
var _inputFields = uiDocument.rootVisualElement.Q("input-message");
_inputFields.RegisterCallback<ChangeEvent<string>>(InputMessage);
}
private void OnDisable()
{
_button.UnregisterCallback<ClickEvent>(PrintClickMessage);
}
private void PrintClickMessage(ClickEvent evt)
{
++_clickCount;
Debug.Log($"{"button"} was clicked!" +
(_toggle.value ? " Count: " + _clickCount : ""));
}
public static void InputMessage(ChangeEvent<string> evt)
{
Debug.Log($"{evt.newValue} -> {evt.target}");
}
}
将 SimpleRuntimeUI.cs 添加为 UIDocument 游戏对象的组件。