UI Toolkit: Is it possible to modify USS custom properties (variables) with C#?

I’m trying to create a crosshair with the new UI toolkit package but I cannot find a way to modify my crosshair variable var(–gap) from within C#.

I can read the value just fine (prints out 550%), but when I try to change it in game nothing happens. Confirmed by the UI debugger window.

Crosshair.cs

    private VisualElement _root;
    private CustomStyleProperty<string> _gap = new CustomStyleProperty<string>("--gap");
     
    private void Start()
    {
        var uiDocument = GameObject.Find("UIDocument");
        _root = uiDocument.GetComponent<UIDocument>().rootVisualElement;
        _root.RegisterCallback<CustomStyleResolvedEvent>(OnCustomStyleResolved);
    }

    private void OnCustomStyleResolved(CustomStyleResolvedEvent  e)
    {
        if (!e.customStyle.TryGetValue(_gap, out var gap)) return;
        gap = "0%";
    }
    ...

Crosshair.uss

.crosshair 
{
    background-color: rgb(0, 255, 17);
    position: absolute;
    --length: 400%;
    --thickness: 40%;
    --minThickness: 1px;
    --minLength: 10px;
    --gap: 550%;
}
3 Likes

I don’t think that’s possible. Usually, you’d have a field to store the value of the CustomStyleProperty, and that’s the field you modify from code. You’d probably also want to store a bool to indicate that the field has been set from code to avoid overwriting it when there’s a new CustomStyleResolvedEvent.

There’s a good example of this in Unity’s own Image element: check how they use m_TintColorIsInline and the tintColor property.

1 Like

Thanks I’ll look into that. I’m pretty sure the out keyword can’t be used for what I need

What do you mean? What do you need to use the out keyword for that doesn’t work for you?

I thought out was like ref but it just copies the value of the --gap property into my C# local variable “gap”

It is like ref in this context, the only difference between an out parameter and a ref parameter is that the out parameter is guaranteed to be assigned by the method that uses it. You would have the same problem if it was a ref parameter. The parameter would still a variable created by you, so it couldn’t be a reference to the original style property.

Maybe you are thinking of ref returns; that does do something similar to what you suggest, but it’s used very differently, and I believe Unity doesn’t use it in any of its public API.

Ohh okay, thank you for explaining.