Version: 6000.3
语言: 中文
在 C# 脚本中获取自定义样式
USS 的最佳实践

在 C# 脚本中应用样式

您可以写信给style将样式值设置为元素。但是,要获取元素的实际渲染样式,请从resolvedStyle.

设置样式

在 C# 脚本中,可以将样式直接设置为style属性视觉元素实例化或派生自 C# 的可视化树的节点VisualElement类。您可以设置外观样式、定义行为并将其作为 UI 的一部分显示在屏幕上。更多信息
请参阅术语表
.例如,以下代码将按钮的背景颜色设置为红色:

button.style.backgroundColor = Color.red

还可以将 Unity 样式表 (USS) 添加到任何视觉元素。Unity 将 USS 文件表示为StyleSheetC# 中的对象脚本一段代码,允许您创建自己的组件、触发游戏事件、随时间修改组件属性以及以您喜欢的任何方式响应用户输入。更多信息
请参阅术语表
.

要将样式表添加到视觉元素:

  1. 负荷StyleSheet对象,例如AssetDatabase.Load()Resources.Load().
  2. 使用styleSheets属性来添加StyleSheet对象。

例如,在局部变量styleSheet和局部变量中的一个元素element,以下示例将样式表添加到元素中:

element.styleSheets.Add(styleSheet);

【注】样式规则适用于视觉元素及其所有后代,但不适用于元素的父级或同级元素。对 USS 文件的任何更改都会自动刷新使用此样式表的 UI。

获取解析的样式

元素上的样式值是从各种来源计算的,包括多个应用类、从祖先继承以及从 UXML 或 C# 代码中继承的内联样式。这些值可能会因帧而异。这style仅保存元素的内联样式,不反映其他来源。这resolvedStyle具有最终计算值,考虑当前帧上的所有源。

例如,当您使用内联样式设置元素的高度时,将styleresolvedStyle从相同的值开始。将元素添加到层次结构中时,resolvedStyle.height可以NaN直到布局更新。如果将类中的高度定义为百分比,则计算的宽度依赖于父属性,例如border-heightpadding.虽然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);

其他资源

在 C# 脚本中获取自定义样式
USS 的最佳实践