Version: 2021.3
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
Copyright © 2023 Unity Technologies
优美缔软件(上海)有限公司 版权所有
"Unity"、Unity 徽标及其他 Unity 商标是 Unity Technologies 或其附属机构在美国及其他地区的商标或注册商标。其他名称或品牌是其各自所有者的商标。
公安部备案号:
31010902002961