Custom VisualElement custom USS Attribute

Hello, I’ve been wondering whether it is possible to implement a custom USS attribute, that we would be able to use in an .uss style sheet? Or whether something like this is planned for the future?

Right now I have a custom VisualElement (eg LineElement) and I would like to define a custom USS attribute (eg line-color), so that I would be able to use that attribute in the style sheet (eg .line { line-color: rgb(…) }).

I am basically looking for a similar functionality that is now available for custom UXML attributes via the UXMLTraits and TypedUxmlAttributeDescription combo.

Custom UXML Attributes I suggested extending the UXMLTrait to allow custom attributes to be defined. I would appreciate your feedback :slight_smile:

@BinaryCats I will check it out, but just in case: my question is about custom USS attributes (not custom UXML attributes)

This is what you’re looking for:
https://docs.unity3d.com/Packages/com.unity.ui@1.0/api/UnityEngine.UIElements.CustomStyleResolvedEvent.html

Here’s an example I randomly extracted from…somewhere:

class MyElement : VisualElement
{
    static readonly CustomStyleProperty<int> k_CellSizeProperty = new CustomStyleProperty<int>("--cell-size");
    static readonly CustomStyleProperty<Color> k_OddCellColorProperty = new CustomStyleProperty<Color>("--odd-cell-color");
    static readonly CustomStyleProperty<Color> k_EvenCellColorProperty = new CustomStyleProperty<Color>("--even-cell-color");

    int m_CellSize;
    Color m_OddCellColor;
    Color m_EvenCellColor;

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

    void OnCustomStyleResolved(CustomStyleResolvedEvent e)
    {
        if (e.customStyle.TryGetValue(k_CellSizeProperty, out var cellSizeProperty))
            m_CellSize = cellSizeProperty;

        if (e.customStyle.TryGetValue(k_OddCellColorProperty, out var oddCellColor))
            m_OddCellColor = oddCellColor;

        if (e.customStyle.TryGetValue(k_EvenCellColorProperty, out var evenCellColor))
            m_EvenCellColor = evenCellColor;
    }
}
2 Likes

@uDamian Thank you, this in fact is exactly what I am looking for! :slight_smile:

1 Like

Sorry to resurrect this thread; but how can I use transition for CustomStyleProperties (without Coroutines for example) and is there an easy way to support shorthand values (like “2px 5px”, “2px 5px 3px 7px”).

1 Like

Unity doesn’t seem to allow something like a CustomStyleProperty, customStyle.TryGetValue just gives an error: Vector2 must be convertible to UnityEngine.Object or something like that.

Anyone know how I could get two floats in one property?

I am using string for that :') and than parse it. So, that way I can use all of the values like “3”, “3 4”, “3 4 6 7” (but UI Toolkit totally need to give us some shortcut to use shorthand values, etc)