UIToolkit是Unity官方推出的最新 UI解决方案,未来将逐步取代现有的UGUI方案,当然现在(2021.7.22)仍处于preview阶段。官方解释这是一套兼顾编辑器和runtime界面开发的更高效的UI框架。
1.创建一个新的项目,unity版本要求2020.2以上

2.打开菜单栏-window-package manager

3.从git链接来添加源:

4.输入com.unity.ui,然后点击add会自动下载:

5.下载完成后,会多出一个uitoolkit并自动安装好了(绿色勾),截止目前(2021.7.22)依旧是preview版本。

UIToolkit使用了uxml来描述界面的布局,使用uss来制作不同样式,参考了web开发的xml和css方案。Unity2021已经将UIToolkit内置在引擎中,具有和UGUI同等地位。
比如要画一个按钮,对应的uxml
<UXML xmlns="UnityEngine.UIElements" xmlns:uie="UnityEditor.UIElements">
<Button text="UXML Button" name="the-uxml-button" />
</UXML>
按钮的样式uss如下
.some-styled-button {
-unity-font-style: bold;
}
在C#代码可以将名字和样式名绑定在一起添加点击事件。
Action action = () =>
{
container.Query<Button>().ForEach((button) =>
{
button.text = button.text.EndsWith("Button") ? "Button (Clicked)" : "Button";
});
};
// Get a reference to the Button from UXML and assign it its action.
var uxmlButton = container.Q<Button>("the-uxml-button");
uxmlButton.RegisterCallback<MouseUpEvent>((evt) => action());
// Create a new Button with an action and give it a style class.
var csharpButton = new Button(action) { text = "C# Button" };
csharpButton.AddToClassList("some-styled-button");
container.Add(csharpButton);
uxml如果都得用手写那显然太麻烦了,所以unity制作了一个可视化编辑工具uibuilder。所以uibuilder需要通过PackageManger安装(unity2021以后的版本已经内置在引擎中)。
6.安装UIToolKit后,需要安装另一个组件:UIBuilder(界面构建器)。打开高级选项:

7.在高级选项中勾选enable preview packages 启用预览包。

8.回到管理界面,切换包的分组源为unity registry

9.找到UIBuilder并安装。

10.安装完毕后回到unity编辑器,在层级面板中右键uitoolkit-ui document

11.在项目面板中创建一个ui document

12.指定层级面板中uidocument的source asset

13.双击打开project目录下的uxml,会打开uibuilder,这个界面下就可以编辑UI元素

14.从containers拖入一个visualement到hierachy中,活着直接拖入viewport中

15.设置size

16.设置位置

17.设置背景颜色

18.保存回到场景即可看到效果(第一次有可能需要play下):

19.从library中添加label并改名为countertext

20.添加一个按钮并改名为counter_button

21.设置对其方式为居中对齐

22.回到编辑器,创建一个脚本:UICounter.cs,挂载到场景的uidocument上,编辑代码:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UIElements;
public class UICounter : MonoBehaviour
{
private Label _counterText;
private Button _counterButton;
// Start is called before the first frame update
void Start()
{
var root = this.GetComponent<UIDocument>().rootVisualElement;
_counterText = root.Q<Label>("Countertext");
_counterButton = root.Q<Button>("Counter_button");
_counterButton.RegisterCallback<ClickEvent>(ev => OnClick());
}
private void OnClick()
{
_counterText.text = $"Click";
}
}
23.看看最终执行的效果

说明:UIToolKit合并Drawcall能力要强于UGUI,如果图集数量在8个以内,字体数量在一个以内UIToolKit可以将所有界面都合并成一个DrawCall,相反在UGUI中就会占9个DrawCallle ,如果界面多了出现叠层DrawCal会更多。
UIToolkit是支持UGUI的Atlas图集的,但其实它支持的是Texture,即使把Sprite都打在一个图集中也不定能能合并DrawCall,它支持Sprite的Tight模式,增加顶点数减少填充率。只要按照绘制的顺序它会将前8个Texture合并成一个DrawCall,或者有N个Image只要它们用的都是这8个图中的任意,这些也会合并成一个 DrawCall。
就目前的情况来说UIToolkit是不可能代替UGUI的,比如UI粒子叠层、美术的K帧动画、3D透视界面、复杂的层次结构界面,这些都不适合。但是有些界面,比如头顶血条+文字、弹窗、对性能要求较高的一部分界面可以考虑使用UIToolkit,几乎都能合并成一个DrawCall。目前官方也表示UIToolkit和UGUI可以混合使用。
网友评论