Button Sprite/Texture change?

I’m using UI Toolkit to build my Game UI with 2021.2.0f1, and I don’t know how to change the Button’s default and Highlight sprite/texture when I hover and press the Button. Is there any tutorial or manual?

Hello, you need to use pseudo classes defined on your Style Sheet (USS file) to accomplish that. You’d use hover for when you hover and active for when you click a button. It works the same way as CSS pseudo classes, you can read about them here (and try some interactive examples even): CSS Pseudo-classes

Hope this helps! :slight_smile:

Thx! I’ve tried that and it worked! But when I use C# code to change the background in runtime, the hover and active become invalidated。
C# code like that

//this is btn_BaseInfo's clicked Event, it try to change the background to highlight and other two button to normal;
private void onBaseInfoBtnClicked(ClickEvent evt)
{
btn_BaseInfo.style.backgroundImage = highlightBackground;
btn_IntelliInspection.style.backgroundImage = normalBackground;
btn_DefectRecord.style.backgroundImage = normalBackground;
}

That’s because you’re inlining your style when you’re using C# to change values (similar to defining those values on the UXML), which takes precedence over USS styles. In order for the pseudoclasses to work, you have to keep using style classes for all styling operations, or unsetting the inlined values once you’re done with them.

To unset an inlined value, assign StyleKeyword.Null to it, example:

btn_BaseInfo.style.backgroundImage = StyleKeyword.Null;