UI Tool一览
UI Toolkit简介
UI Toolkit是替代UGUI和IMGUI的新UI方案,但到目前为止依然没有成为主流的UI系统.UI Toolkit相对UGUI和IMGUI依然有一些不足的地方.
Editor | Runtime | |
---|---|---|
UI Toolkit | 最早推出的时候并开始支持 | 2020版本之后才支持 |
UGUI | 不支持 | 支持 |
IMGUI | 支持 | 不支持 |
UI Toolkit安装
editor
unity从2019开始已经默认安装了ui toolkit的editor版本
runtime
-
unity从2020版本以及2021.1版本中需要使用package安装runtime.
通过Package Manager安装:- 打开Package Manager之后点击左上角的+
- 从菜单中选择 Add package from git URL…
- 输入com.unity.ui 之后点击Add即可
-
unity从2021.1版本开始已经将runtime的package包内嵌到了unity中
简单使用
添加editor代码
在project 视图里通过Create/UI Toolkit/Editor Window菜单即可创建一个editor脚本
点击confirm之后会在project中生成三个文件,分别TestEditor.cs,TestEditor.uss和TestEditor.uxml
- cs代码放的就是逻辑
- uss用于描述样式
- uxml用于描述view
public class TestEditor : EditorWindow
{
[MenuItem("Window/UI Toolkit/TestEditor")]
public static void ShowExample()
{
TestEditor wnd = GetWindow<TestEditor>();
wnd.titleContent = new GUIContent("TestEditor");
}
public void CreateGUI()
{
// Each editor window contains a root VisualElement object
VisualElement root = rootVisualElement;
// VisualElements objects can contain other VisualElement following a tree hierarchy.
VisualElement label = new Label("Hello World! From C#");
root.Add(label);
// Import UXML
var visualTree = AssetDatabase.LoadAssetAtPath<VisualTreeAsset>("Assets/Editor/TestEditor.uxml");
VisualElement labelFromUXML = visualTree.Instantiate();
root.Add(labelFromUXML);
// A stylesheet can be added to a VisualElement.
// The style will be applied to the VisualElement and all of its children.
var styleSheet = AssetDatabase.LoadAssetAtPath<StyleSheet>("Assets/Editor/TestEditor.uss");
VisualElement labelWithStyle = new Label("Hello World! With Style");
labelWithStyle.styleSheets.Add(styleSheet);
root.Add(labelWithStyle);
}
}
从上述的TestEditor.cs代码中我们不难发现:
- 可以通过代码的方式添加VisualElement
- 可以通过uxml的方式添加VisualElement
- uss样式可以添加到我们任意想限制的element上
Runtime下使用
在hierarchy中添加UIDocument即可,UIDocument上有两个重要元素
- panel settings:定义了一些全局是配置,比如字体、样式等信息
- Source Asset:即之前说的uxml
[以上是个人的一点记录,后续将继续更新ui toolkit的知识]