Search Unity

Question Change value on USS custom property through C#

Discussion in 'UI Toolkit' started by sandstedt, Mar 20, 2023.

  1. sandstedt

    sandstedt

    Joined:
    May 24, 2015
    Posts:
    67
    I have a set of color variables in :root in the root node stylesheet.

    upload_2023-3-20_8-51-12.png

    What I want to do, is to dynamically change these colors base on the current theme of the match (each match has it's own color theme). Coudn't find any documentation how to change these custom properties through code.

    Found some references through a forum post here: https://github.com/Unity-Technologi...ides/com.unity.ui/Core/Controls/Image.cs#L334

    But not sure how I would implement that in my code. Also not sure how to convert a regular Color to a UIElements color.

    upload_2023-3-20_8-54-26.png
     
  2. sandstedt

    sandstedt

    Joined:
    May 24, 2015
    Posts:
    67
    Ended up adding a class on the root-element, and redeclaring the variables in that class. Ex

    Code (USS):
    1. .dark-mode {
    2.   --ui-color: rgb(255,255,255);
    3.   --ui-bg: rgb(0,0,0);
    4. }

    But still would like to find a way to declare this through code so it can be a bit more dynamic.
     
  3. noirb

    noirb

    Joined:
    Apr 10, 2014
    Posts:
    84
    AFAIK, you can't over-write these values at run-time. But what you *can* do is create multiple themes, each of which contains different definitions for these variables and then switch between them at runtime.

    I'm sure there are quite a few ways to set this up depending on your needs, but for example you can do something like:

    • MainTheme.tss
      : The default theme in your panelsettings. Contains all of your regular stylesheets, which depend on
      var(--ui-color)

    • DefaultStyle.uss
      : Defines
      --ui-color: rgb(255, 255, 255)
      .
    • AltStyle.uss
      : Defines
      --ui-color: rgb(0, 0, 0)
      • NOT included in
        MainTheme.tss
    • AltTheme.tss
      : Inherits from
      MainTheme
      , and includes
      AltStyle.uss

    Then in code, you swap themes on your UIDocument(s), perhaps by loading them from Resources or something:
    Code (CSharp):
    1. public class ThemeSwitcher : MonoBehaviour
    2. {
    3.   public void OnSwitchThemeButtonPressed()
    4.   {
    5.     GetComponent<UIDocument>().panelSettings.themeStyleSheet = Resources.Load<ThemeStyleSheet>("AltTheme");
    6.   }
    7. }
     
  4. sandstedt

    sandstedt

    Joined:
    May 24, 2015
    Posts:
    67
    Oh I didn't even know that there was a thing called theme . Thanks for the info @noirb. Definitely will make things a bit easier. But would be really good to be able to override these variables (custom properties) in runtime, the same as you can to in standard CSS.
     
  5. Mj-Kkaya

    Mj-Kkaya

    Joined:
    Oct 10, 2017
    Posts:
    179
    Yes it is! Exactly what I need.
     
    FerdowsurAsif likes this.