Version: 2023.1
Language : English
USS built-in variable references
Best practices for USS

Apply styles in C# scripts

In a C# script, you can set styles directly to the style properties of a visual elementA node of a visual tree that instantiates or derives from the C# VisualElement class. You can style the look, define the behaviour, and display it on screen as part of the UI. More info
See in Glossary
. For example, the following code sets the background color of a button to red:

button.style.backgroundColor = Color.red

You can also add a Unity style sheet (USS) to any visual element. Unity represents USS files as StyleSheet objects in C# scriptsA piece of code that allows you to create your own Components, trigger game events, modify Component properties over time and respond to user input in any way you like. More info
See in Glossary
.

To add style sheets to a visual element:

  1. Load StyleSheet objects with standard Unity APIs such as AssetDatabase.Load() or Resources.Load().
  2. Use the styleSheets property of a visual element to add the StyleSheet object.

For example, given a style sheet in the local variable styleSheet and an element in the local variable element, the following example adds the style sheet to the element:

element.styleSheets.Add(styleSheet);

Note: Style rules apply to the visual element and all its descendants, but don’t apply to the parent or siblings of the element. Any change to the USS file automatically refreshes the UI(User Interface) Allows a user to interact with your application. Unity currently supports three UI systems. More info
See in Glossary
that uses this style sheet.

Additional resources

USS built-in variable references
Best practices for USS