UI Toolkit change background and the hover color via script

I have to create standard UI Toolkit buttons from code. Styling is done via code because I need to set button background colors procedurally.

Using button.style.backgroundColor = Color.White replaces the connected Unity stylesheet. Thus I lose hover highlighting.

Question: How can I set the hover background color from code?

Hey!

Applying inline styles will override any other styles on the element. I’d suggest using a class instead. Here’s an example:

USS:

.custom-button {
    background-color: white;
}

C#:

myButton.AddToClassList("custom-button");

Thanks for the example. Actually I have not used USS files yet. Do I need an actual file or can this be created in memory as a simple string?

Hey! Yes, you’ll need a USS file. You can learn more about USS in the following documentation.

For a simple example to get you started, you can also easily create a UI Toolkit Window using the following menu item: Create/UI Toolkit/Editor Window

Ah, that’s too bad. I’d wish there was some kind of generic way to create USS data. Creating a USS file does in my case not work, because it is “hardcoding” the color.

A simplified abstraction of the code I am using looks like this:

int flexButtonCount = 16;
Button[] buttons = new Button[flexButtonCount];
for( int i = 0; i < flexButtonCount; i++ )
{
	buttons[i] = new();
	buttons[i].style.backgroundColor = Color.HSVToRGB( ( float )i / flexButtonCount, 1f, 1f ); // procedural color generation
}

Guess I have to do the hover highlight effect using a mouse over event?

PS: Ok, that was pretty easy:

button.RegisterCallback( ( MouseOverEvent evt ) => button.style.backgroundColor = color );
button.RegisterCallback( ( MouseLeaveEvent evt ) => button.style.backgroundColor = color.MultiplyRGB( 0.75f ) );

Maybe for helping, you can write like that :


        NewGameButton = UIDocument.rootVisualElement.Q<Button>("NewGameButton");
        NewGameButton.SetEnabled(true);
        NewGameButton.RegisterCallback<ClickEvent>(OnLaunchNewGame);
        NewGameButton.RegisterCallback<MouseOverEvent>((MouseOverEvent e) => NewGameButton.style.color = Color.red);

Just, keep in mind that you need to manage when the mouse get away :slight_smile: