每个 VisualElement
都包含样式属性,这些属性用于设置元素的尺寸以及元素在屏幕上的绘制方式,例如 backgroundColor
或 borderColor
。
样式属性可以在 C# 中设置,也可以在样式表中设置。样式属性在其自己的数据结构(IStyle
接口)中重新分组。
UI 工具包支持用 USS(Unity 样式表)编写的样式表。USS 文件是受 HTML 中的层叠样式表 (CSS) 启发的文本文件。USS 格式与 CSS 类似,但 USS 包括一些覆盖和自定义以便于更好地与 Unity 协同工作。
本节详细介绍 USS、其语法以及与 CSS 的差异。
Unity 样式表 (USS) 的基本构成元素如下:
.uss
扩展名。样式规则的一般语法如下:
selector {
property1:value;
property2:value;
}
可以将 Unity 样式表 (USS) 附加到任何视觉元素。样式规则适用于视觉元素及其所有后代。必要时,还会自动重新应用样式表。
应使用标准 Unity API(如 AssetDatabase.Load()
或 Resources.Load()
)来加载 StyleSheet
对象。使用 VisualElement.styleSheets.Add()
方法可将样式表附加到视觉元素。
如果在 EditorWindow
运行时修改 USS 文件,则会立即应用样式更改。
样式的应用过程对于使用 UI 工具包 的开发者是透明的。需要时(层级视图更改、样式表重新加载)会自动重新应用样式表。
定义样式表后,可以将其应用于视觉元素树。
在此过程中,选择器将与元素进行对比,从而解析从 USS 文件应用的属性。如果选择器与元素匹配,则样式声明将应用于元素。
例如,以下规则匹配任何 Button
对象:
Button {
width: 200px;
}
UI 工具包使用以下条件将视觉元素与其样式规则相匹配:
name
属性以上这些特征可用于样式表中的选择器。
如果您熟悉 CSS,应该可以看出其与 HTML 标签名称、id
属性和 class
属性之间的相似性。
Did you find this page useful? Please give it a rating:
Thanks for rating this page!
What kind of problem would you like to report?
Thanks for letting us know! This page has been marked for review based on your feedback.
If you have time, you can provide more information to help us fix the problem faster.
Provide more information
You've told us this page needs code samples. If you'd like to help us further, you could provide a code sample, or tell us about what kind of code sample you'd like to see:
You've told us there are code samples on this page which don't work. If you know how to fix it, or have something better we could use instead, please let us know:
You've told us there is information missing from this page. Please tell us more about what's missing:
You've told us there is incorrect information on this page. If you know what we should change to make it correct, please tell us:
You've told us this page has unclear or confusing information. Please tell us more about what you found unclear or confusing, or let us know how we could make it clearer:
You've told us there is a spelling or grammar error on this page. Please tell us what's wrong:
You've told us this page has a problem. Please tell us more about what's wrong:
Thank you for helping to make the Unity documentation better!
Your feedback has been submitted as a ticket for our documentation team to review.
We are not able to reply to every ticket submitted.