您可以对 style 进行写入操作,从而为元素设置样式值。但是,要获取元素的实际渲染样式,请从 resolvedStyle 读取。
在 C# 脚本中,您可以将样式直接设置为视觉元素的 style 属性。例如,以下代码将按钮的背景颜色设置为红色:
button.style.backgroundColor = Color.red
还可以将 Unity 样式表 (USS) 添加到任何视觉元素。Unity 将 USS 文件表示为 C# 脚本中的 StyleSheet 对象。
要将样式表添加到视觉元素:
AssetDatabase.Load() 或 Resources.Load())加载 StyleSheet 对象。styleSheets 属性添加 StyleSheet 对象。例如,当给定局部变量 styleSheet 中的样式表和局部变量 element 中的元素时,以下示例会将样式表添加到元素:
element.styleSheets.Add(styleSheet);
注意:样式规则适用于视觉元素及其所有后代,但不适用于元素的父级或同级。对 USS 文件的任何更改都会自动刷新使用此样式表的__ UI__(即用户界面,User Interface)让用户能够与您的应用程序进行交互。Unity 目前支持三种 UI 系统。更多信息
See in Glossary。
元素的样式值是从各种来源计算的,包括应用的多个类、从祖先元素继承的样式,以及来自 UXML 或 C# 代码的内联样式。这些值可能会因帧而异。style 仅保存元素的内联样式,不反映其他来源。resolvedStyle 具有最终计算值,考虑了当前帧上的所有源。
例如,使用内联样式设置元素的高度时,style 和 resolvedStyle 都以相同的值开头。在将元素添加到层级视图时,布局更新之前,resolvedStyle.height 可能为 NaN。如果将类中的高度定义为百分比,则计算的宽度依赖于父属性,例如 border-height 和 padding。虽然 style.height 可能给出相对值,例如对于可更改值的过渡,但 resolvedStyle.height 会给出实际渲染高度。
要在几何体更改时获取解析的样式,可以使用 GeometryChangedEvent 事件。当 VisualElement 的布局发生变化(包括大小和位置的变化)时触发此事件。您可以为此事件注册回调,并在回调中访问 VisualElement 的 resolvedStyle 属性以获取最终计算的样式。
以下示例创建了一个自定义编辑器窗口并记录元素的解析高度。如果调整窗口大小,元素的高度会发生变化:
using UnityEditor;
using UnityEngine;
using UnityEngine.UIElements;
public class ResolvedStyles : EditorWindow
{
[MenuItem("Window/UI Toolkit/ResolvedStyles")]
public static void ShowExample()
{
GetWindow<ResolvedStyles>();
}
private void OnEnable()
{
titleContent = new GUIContent("Resolved Styles");
}
public void CreateGUI()
{
VisualElement root = rootVisualElement;
// Element that is tracked.
// When you resize the Editor window, the inner content is not necessarily updated
// during the drag operation. The resolved height field is updated whenever the drag
// operation is complete.
var element = new VisualElement
{
style =
{
flexGrow = 1,
backgroundColor = Color.red
}
};
root.Add(element);
// Register a callback for the GeometryChangedEvent
element.RegisterCallback<GeometryChangedEvent>(OnGeometryChanged);
}
// Callback for the GeometryChangedEvent
public void OnGeometryChanged(GeometryChangedEvent evt)
{
// Get the VisualElement that triggered the event
VisualElement element = evt.target as VisualElement;
// Get the resolved style of the VisualElement
float height = element.resolvedStyle.height;
// Log the resolved of the VisualElement
Debug.Log("Resolved height: " + height);
}
}
如果元素的几何体没有变化,则可以添加一个调度程序来定期检查元素的解析样式:
element.schedule.Execute(() =>
{
Debug.Log(element.resolvedStyle.height);
}).Every(100);