Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. We have updated the language to the Editor Terms based on feedback from our employees and community. Learn more.
    Dismiss Notice

Question Button Sprite/Texture change?

Discussion in 'UI Toolkit' started by liekong1991, Nov 5, 2021.

  1. liekong1991

    liekong1991

    Joined:
    Nov 15, 2014
    Posts:
    12
    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?
     
  2. JuliaP_Unity

    JuliaP_Unity

    Unity Technologies

    Joined:
    Mar 26, 2020
    Posts:
    666
    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): https://www.w3schools.com/css/css_pseudo_classes.asp

    Hope this helps! :)
     
  3. liekong1991

    liekong1991

    Joined:
    Nov 15, 2014
    Posts:
    12
    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;
    }
     
    Last edited: Nov 8, 2021
  4. JuliaP_Unity

    JuliaP_Unity

    Unity Technologies

    Joined:
    Mar 26, 2020
    Posts:
    666
    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:

    Code (CSharp):
    1. btn_BaseInfo.style.backgroundImage = StyleKeyword.Null;