In a C# script, you can set styles directly to the style
properties of a visual element. 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# scripts.
To add style sheets to a visual element:
StyleSheet
objects with standard Unity APIs such as AssetDatabase.Load()
or Resources.Load()
.styleSheets
property of a visual element to add the StyleSheet
object.For example, given a style sheet in local variable styleSheet
and an element in 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 that uses this style sheet.