3

Unity3D研究院之UIToolkit运行时初探

 2 years ago
source link: https://www.xuanyusong.com/archives/4893
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

Unity3D研究院之UIToolkit运行时初探

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 to perform when button is pressed.
// Toggles the text on all buttons in 'container'.
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);

UIToolkit同时支持Editor和Runtime两种解决方案,之前的OnGUI已经完全被废弃。就目前的技术来看在编辑模式下UIToolkit可以完全代替之前的面板制作。如下图所示,官方提供了丰富的案例Editor模式下很容易制作。

uxml如果都得用手写那显然太麻烦了,所以unity制作了一个可视化编辑工具uibuilder。所以UIToolkit和uibuilder都需要通过PackageManger安装(unity2021以后的版本已经内置在引擎中)

今天的主角并非Editor模式,而是Runtime运行时。如下图所示,我们制作一个简单的界面。包括图片和文字,uitoolkit已经内置了Text Mesh Pro支持图文混排。

Unity3D研究院之UIToolkit运行时初探 - 雨松MOMO程序研究院 - 2如下图所示绑定UIDocument随后将uxmal拖上去就可以了,下面还可以设置Sort Order

Unity3D研究院之UIToolkit运行时初探 - 雨松MOMO程序研究院 - 3
如果使用UGUI,每个图集是一个DrawCall,每个字体占一个DrawCall,如下图所示,这里占用了3个DrawCall。

Unity3D研究院之UIToolkit运行时初探 - 雨松MOMO程序研究院 - 4
同样的界面用uitoolkit在制作一遍,能看出它们会合并成1个Drawcall性能显然比UGUI要好。为什么UIToolkit能合并Drawcall呢?请大家看又下角红框中,如果图集数量在8个以内,字体数量在1个以内UIToolkit可以将所有界面都合并成1个DrawCall,相反在UGUI中就会占9个Drawcall了,如果界面多了出现叠层Drawcall会更多。

Unity3D研究院之UIToolkit运行时初探 - 雨松MOMO程序研究院 - 5
UIToolkit是支持UGUI的Atlas图集的,UIToolkit只有超过8个图集和1个字体时才会占用多个Drawcall。UGUI合并图集的原理是底层真的在合并Mesh,而UIToolkit的方案是通过MaterialBlock传数据进去,并非像UGUI那种合并Mesh。

就目前的情况来说UIToolkit是不可能代替UGUI的,比如UI粒子叠层、美术的K帧动画、3D透视界面、复杂的层次结构界面,这些都不适合。但是有些界面,比如头顶血条+文字、弹窗、对性能要求较高的一部分界面可以考虑使用UIToolkit,几乎都能合并成一个DrawCall。目前官方也表示UIToolkit和UGUI可以混合使用。

我目前对UIToolkit也比较感兴趣,欢迎有志同道合的朋友一起讨论。

作者:雨松MOMO
专注移动互联网,Unity3D游戏开发
捐 赠写博客不易,如果您想请我喝一杯星巴克的话?就进来看吧!

留下一个回复 取消回复

你的email不会被公开。

评论

显示名称 *

电子邮箱地址 *

网站地址

在此浏览器中保存我的显示名称、邮箱地址和网站地址,以便下次评论时使用。


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK