Change value on USS custom property through C#

I have a set of color variables in :root in the root node stylesheet.

8888322--1215372--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: UnityCsReference/ModuleOverrides/com.unity.ui/Core/Controls/Image.cs at c84064be69f20dcf21ebe4a7bbc176d48e2f289c · Unity-Technologies/UnityCsReference · GitHub

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

Ended up adding a class on the root-element, and redeclaring the variables in that class. Ex

.dark-mode {
  --ui-color: rgb(255,255,255);
  --ui-bg: rgb(0,0,0);
}

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

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:

public class ThemeSwitcher : MonoBehaviour
{
  public void OnSwitchThemeButtonPressed()
  {
    GetComponent<UIDocument>().panelSettings.themeStyleSheet = Resources.Load<ThemeStyleSheet>("AltTheme");
  }
}

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.

Yes it is! Exactly what I need.

1 Like