Version: Unity 6.0 (6000.0)
语言 : 中文
USS 内置变量引用
在 C# 脚本中应用样式

在 C# 脚本中获取自定义样式

可以使用 VisualElement.customStyle 属性获取应用于元素的自定义样式属性(变量)的值。但是,不能像使用 VisualElement.styleVisualElement.resolvedStyle 那样直接查询。相反,请执行以下操作:

  1. 注册到 CustomStyleResolvedEvent 事件。
  2. 调用 TryGetValues 方法来查询 element.customStyle 属性的返回对象。

假设已在 USS 中定义了自定义样式属性 --my-custom-color,如下所示:

.my-selector
{
    --my-custom-color: red;
}

以下示例类展示了如何获取应用于元素的 --my-custom-color 值:

public class HasCustomStyleElement : VisualElement
{
    // Custom style property definition from code indicating the type and the name of the property.
    private static readonly CustomStyleProperty<Color> s_CustomColor = new ("--my-custom-color");

    private Color customColor { get; set; }

    public HasCustomStyleElement()
    {
        RegisterCallback<CustomStyleResolvedEvent>(OnCustomStyleResolved);
    }

    private void OnCustomStyleResolved(CustomStyleResolvedEvent evt)
    {
        // If the custom style property is resolved for this element, you can query its value through the `customStyle` accessor.
        if (evt.customStyle.TryGetValue(s_CustomColor, out var value))
        {
            customColor = value;
        }
        // Otherwise, put some default value.
        else
        {
            customColor = new Color();
        }
    }
}

其他资源

USS 内置变量引用
在 C# 脚本中应用样式