Search Unity

Active/Selected styling

Discussion in 'UIElements' started by cecarlsen, Jun 21, 2019.

  1. cecarlsen

    cecarlsen

    Joined:
    Jun 30, 2006
    Posts:
    522
    Is there a native way to style active/selected elements (for example like in CSS "className:active") ... or should I manually add and remove a "selected" style from CSS inside a manipulator using AddToClassList and RemoveFromClassList?
     
  2. antoine-unity

    antoine-unity

    Unity Technologies

    Joined:
    Sep 10, 2015
    Posts:
    102
    Hello,

    This is technically supported from the style sheets but there is no public API to set those states (pseudo states). Right now you'll have to use the class list to achieve what you need.

    However if you use the
    Clickable
    manipulator it will set the ":active" state.

    The full list of existing pseudo states is detailed here: https://docs.unity3d.com/2019.3/Documentation/Manual/UIE-USS-Selectors.html under "Pseudo states".
     
    Last edited: Jun 28, 2019
    cecarlsen likes this.
  3. Kamyker

    Kamyker

    Joined:
    May 14, 2013
    Posts:
    60
    +1 to add public API.

    Not sure if bug but after setting backgroundImage in C# the background-image in ":hover" state defined in uss stops working.
     
  4. jonathanma_unity

    jonathanma_unity

    Unity Technologies

    Joined:
    Jan 7, 2019
    Posts:
    61
    Hi Kamyker, this is expected behavior since setting style with C# is considered "inline", this means that they have the highest specificity and cannot be set in USS afterwards.
     
  5. Kamyker

    Kamyker

    Joined:
    May 14, 2013
    Posts:
    60
    Yes but I'm not setting any value for :hover state in C# as it's not even possible. Not sure if I was clear enough.

    In USS:
    Code (USS):
    1. #icon {
    2.     background-image: url(icon.png);
    3. }
    4. #icon:hover {
    5.     background-image: url(iconHover.png);
    6. }
    In C#/USS:
    Code (CSharp):
    1. button.style.backgroundImage = new Background(AssetDatabase.LoadAssetAtPath<Texture2D>(path));
    Code (USS):
    1. #icon:hover {
    2.     background-image: url(iconHover.png);
    3. }
    Is it because setting button.style.backgroundImage clears info for all the states? If so then it's pretty weird and could be split to button.styles[PseudoStates.Hover] etc.
     
  6. jonathanma_unity

    jonathanma_unity

    Unity Technologies

    Joined:
    Jan 7, 2019
    Posts:
    61
    When you do this this basically take over all USS. The element is assigned this background image and will keep it unless you change it from C#. Even though "#icon:hover" will match the style set from C# wins because it has higher specificity...

    If you remove that line it should work as expected.