How to replace by script the style assigned to an element (button) in UI builder?

Apologize for simple, noobish question:
In UI builder I have created one button and two styles - “butLang-style” and “butShow-style” (see picture).
The first style (“butLang-style”) was then assigned to the button (drag&drop).
Then, during the “game”, I want to apply the second style to the button (to change its appearance etc.).
I can successfully get the buttons reference in the script for example by

butLangCZ = uiRoot.Q<Button>("but_lang_cz");

but could not find the way how to say …apply to the button “butLangCZ” the style called “butShow-style”.

Was not able to find anything useful both in tutorials and documentation.
Help would be greatly appreciated…

button.AddToClassList(“myClassName”);

button.style.display = DisplayStyle.flex;

2 Likes

Assuming you’re talking about applying a class, calling AddToClassList on your button variable is the way to go. So with the names you provided, it should look something like this:

butLangCZ = uiRoot.Q<Button>("but_lang_cz");
butLangCZ.AddToClassList("butShow-style");

If “butShow-style” is a Style Sheet (not entirely clear from the way you wrote), you’d call AddStyleSheet on your button variable instead, so something like this (assuming you already loaded your Style Sheet in a variable named butShowStyle):

butLangCZ = uiRoot.Q<Button>("but_lang_cz");
butLangCZ.AddStyleSheet(butShowStyle);
1 Like

Great, thanks both of you @JuliaP_Unity and @manuelgoellnitz for quick and clear response!

Sorry to bother @JuliaP_Unity with one additional detail regarding applying a class to a button:

myButton.AddToClassList("butNew-style");

works nicely per your advice.
However - can the class be changed multiple times during the game? For example changed back to the old/initial one - something like

myButton.AddToClassList("butOld-style");

Based on my tests it does not seem so…?

Additional note to the topic - possible solution:
The UI Toolkit debugger shows, that:

  • after assigning the new “visual” class to the element/button using “…AddToClassList(“butNew-style”)…” as advised, both the original and new class are now attached to the element.
  • when I want to return to the original look/class using “…AddToClassList(“butOld-style”)…” the element retains the look of the “butNew-style”.
    The problem can be possibly solved by removing the butNew-style from the class list or just temporarily disable it using the method described here

Hey @ivank as you noticed this is about both classes being there and their order! The latest one added will have precedence over the one that was already there.

You can either remove the other class (element.RemoveFromClassList("class-name")), or toggle it (element.ToggleInClassList("class-name")).

All of the documentation can be found in the VisualElement scripting reference page.

1 Like