You can write to style
to set style values to an element. However, to get the final computed styles of an element, read from resolvedStyle
.
C# 스크립트에서는 시각적 요소의 ‘style’ 프로퍼티에 직접 스타일을 설정할 수 있습니다.예를 들어 다음 코드는 버튼의 배경색을 빨간색으로 설정합니다.
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.
시각적 요소에 스타일시트를 추가하려면 다음 단계를 따르십시오.
StyleSheet
objects with standard Unity APIs, such as AssetDatabase.Load()
or Resources.Load()
.styleSheets
프로퍼티를 사용하여 StyleSheet
오브젝트를 추가합니다.예를 들어, 로컬 변수 ’styleSheet’에 스타일시트가 있고 로컬 변수 ’element’에 요소가 있다고 가정하면 다음 예제에서는 스타일시트를 요소에 추가합니다.
element.styleSheets.Add(styleSheet);
참고:스타일 규칙은 시각적 요소와 그 모든 자손에 적용되지만 요소의 부모 또는 형제에는 적용되지 않습니다.USS 파일을 변경하면 이 스타일시트를 사용하는 UI가 자동으로 새로 고침됩니다.
Style values on an element are computed from various sources, including multiple applied classes, inheritance from ancestors, and inline styles from UXML or C# code. These values might change from frame to frame. The style
only holds the inline styles for the element and does not reflect other sources. The resolvedStyle
has the final calculated values, considering all sources on the current frame.
For example, when you use the inline style to set the width for an element, both the style
and resolvedStyle
start with the same value. When the element is added to the hierarchy, resolvedStyle.width
could be NaN
until the layout updates. If you define the width in a class as a percentage, the computed width relies on parent properties such as border-width
and padding
. Although style.width
might give a relative value, such as for transitions that can change value, resolvedStyle.width
gives the actual rendered width.
The following example shows how to get the final computed width of an element:
float width = element.resolvedStyle.width;