Version: Unity 6.0 (6000.0)
言語 : 日本語
USS ビルトイン変数のリファレンス
C# スクリプトでスタイルを適用する

C# スクリプトでスタイルを取得する

VisualElement.customStyle プロパティを使用して、要素に適用された カスタムスタイルプロパティ (変数) の値を取得できます。ただし、VisualElement.styleVisualElement.resolvedStyle のように直接クエリすることはできません。代わりに、以下の手順に従います。

  1. CustomStyleResolvedEvent イベントに登録します。
  2. TryGetValues メソッドを呼び出し、element.customStyle プロパティの返されたオブジェクトをクエリします。

USS でカスタムスタイルプロパティ --my-custom-color を以下のように定義したとします。

.my-selector
{
    --my-custom-color: red;
}

以下のサンプルクラスは、要素に適用された --my-custom-color の値を取得する方法を示しています。

public class HasCustomStyleElement : VisualElement
{
    // Custom style property definition from code indicating the type and the name of the property.
    private static readonly CustomStyleProperty<Color> s_CustomColor = new ("--my-custom-color");

    private Color customColor { get; set; }

    public HasCustomStyleElement()
    {
        RegisterCallback<CustomStyleResolvedEvent>(OnCustomStyleResolved);
    }

    private void OnCustomStyleResolved(CustomStyleResolvedEvent evt)
    {
        // If the custom style property is resolved for this element, you can query its value through the `customStyle` accessor.
        if (evt.customStyle.TryGetValue(s_CustomColor, out var value))
        {
            customColor = value;
        }
        // Otherwise, put some default value.
        else
        {
            customColor = new Color();
        }
    }
}

追加リソース

USS ビルトイン変数のリファレンス
C# スクリプトでスタイルを適用する
Copyright © 2023 Unity Technologies
优美缔软件(上海)有限公司 版权所有
"Unity"、Unity 徽标及其他 Unity 商标是 Unity Technologies 或其附属机构在美国及其他地区的商标或注册商标。其他名称或品牌是其各自所有者的商标。
公安部备案号:
31010902002961