Closed6

Unity の UI Toolkit をざっくり理解する

Kenta WatashimaKenta Watashima

UI Toolkit の構成要素は 2 つ。Web でいう HTML/CSS に影響を受けて設計されている。Web 開発と同じテンションで書けるので、慣れていれば非常に扱いやすい。

UXML

https://docs.unity3d.com/ja/2021.3/Manual/UIE-UXML.html

XML ベースの専用マークアップ言語。HTML に相当する。レイアウトの意味的な構造(Semantics)を定義する。

<ui:UXML xmlns:ui="UnityEngine.UIElements" xmlns:uie="UnityEditor.UIElements" xsi="http://www.w3.org/2001/XMLSchema-instance" engine="UnityEngine.UIElements" editor="UnityEditor.UIElements" noNamespaceSchemaLocation="../../../UIElementsSchema/UIElements.xsd" editor-extension-mode="False">
    <ui:VisualElement style="flex-grow: 1; background-color: rgba(0, 0, 0, 0);">
        <ui:Label tabindex="-1" text="Label" display-tooltip-when-elided="true" />
        <ui:Button text="Button" display-tooltip-when-elided="true" />
    </ui:VisualElement>
</ui:UXML>

USS

https://docs.unity3d.com/ja/2021.3/Manual/UIE-USS.html

スタイルや見た目を担当。CSS と記法がほぼ一緒だが、対応しているプロパティは異なる。
サポートされているプロパティはここで確認できる。
https://docs.unity3d.com/ja/2021.3/Manual/UIE-USS-SupportedProperties.html

レイアウトは基本的に flex ベースで組む。セレクタの指定には idclass が使え、Label Button などのタグ名を直接指定することもできる。

Kenta WatashimaKenta Watashima

アニメーション

CSS の transition みたくアニメーションを記述できる。

.selectable-button {
    background-color: white;
    border-color: black;
    border-width: 2px;
    transition-duration: 0.3s;
    transition-timing-function: ease-in-out-cubic;
}

.selectable-button:hover {
    background-color: rgb(137, 186, 215);
}

.selectable-button.selected {
    color: #eee;
    background-color: #006BAB;
    border-color: white;
}

ただし、CSS でいう animation プロパティのように、アニメーションをループさせるのは現状ではできなさそう。hover 時や選択時など、状態が変化するときに使う。

Kenta WatashimaKenta Watashima

UQuery

UXMLで定義された要素へのアクセスは UQuery という jQuery ライクな拡張メソッドを使う。いかにもな名前。

[SerializeField] private UIDocument _uiDocument;

private void Start()
{
    Button button = _uiDocument.rootVisualElement.Q<Button>("button-name");
}

ここで取得される Button は uGUI の UnityEngine.UI.Button ではなく、UnityEngine.UIElements.Button となる。

Kenta WatashimaKenta Watashima

VS Code で USS を Syntax Highlight したい

USS に対応している拡張機能がないので、エディタの設定で *.uss*.css に紐づける。どのみち記法が一緒なので、ほとんど問題にならないはず。

settings.json
"files.associations": {
    "*.uss": "css",
}
Kenta WatashimaKenta Watashima

UI Builder

UI Element を編集できる専用の WYSIWYG エディタ。GUI でレイアウトが組めて、その結果が UXML として出力される。

基本は UI Builder 上でレイアウトを組み、スタイリングは USS で直接記述する感じか。この手の GUI エディタは経験上、出力されるソースファイルが汚くなりがちで、あまり信用ならないけれども。

このスクラップは2023/12/07にクローズされました