Unity 6.3
0 онлайн 54 гостей 3 в системе
Вход

Получить пользовательские стили в C# скрипты

Вы можете использовать свойство VisualElement.customStyle для получения значения свойства пользовательского стиля (переменные), примененного к элементу. Однако, вы не можете напрямую запросить его, как это можно сделать с VisualElement.style или VisualElement.resolvedStyle. Вместо этого выполните следующее:

  1. Зарегистрироваться на мероприятие CustomStyleResolvedEvent.
  2. Вызов метода TryGetValues для запроса возвращенного объекта свойства element.customStyle.

Предположим, что вы определили свойство пользовательского стиля --my-custom-color в USS следующим образом:

.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();
        }
    }
}

Дополнительные ресурсы