バージョン: 2021.3+
この例では、UXML テンプレートを使用してバインディングパスを設定する方法を説明します。
この例では、アセットメニュー項目を作成します。このメニューは、GameSwitch オブジェクトのプロパティにバインドする 3 つのテンプレートインスタンスを含む GameSwitch アセットを作成します。
この例で完成したファイルは、この GitHub リポジトリ にあります。
このガイドは、Unity エディター、UI Toolkit、および C# スクリプトに精通している開発者を対象としています。始める前に、以下の点を理解しておいてください。
GameSwitch 構造体を定義するスクリプトと、GameSwitch 構造体のプロパティを保持するカスタムアセットを作成します。
Unity で任意のテンプレートを使用してプロジェクトを作成します。
Project ウィンドウで bind-uxml-template という名前のフォルダーを作成し、すべてのファイルを保存します。
GameSwitch.cs という名前の C# スクリプトを作成し、そのコンテンツを以下のように置き換えます。
using System;
[Serializable]
public struct GameSwitch
{
public string name;
public bool enabled;
}
GameSwitchesAsset.cs という名前の C# スクリプトを作成し、そのコンテンツを以下のように置き換えます。
using UnityEngine;
[CreateAssetMenu(menuName = "UIToolkitExamples/GameSwitches")]
public class GameSwitchesAsset : ScriptableObject
{
public GameSwitch useLocalServer;
public GameSwitch showDebugMenu;
public GameSwitch showFPSCounter;
// Use the Reset function to provide default values
public void Reset()
{
useLocalServer = new GameSwitch() { name = "Use Local Server", enabled = false };
showDebugMenu = new GameSwitch() { name = "Show Debug Menu", enabled = false };
showFPSCounter = new GameSwitch() { name = "Show FPS Counter", enabled = true };
}
}
各 GameSwitch 構造体インスタンスに使用できる UXML テンプレートと、そのテンプレートを使用する UXML ファイルを作成します。
game_switch.uxml という名前の UI Document を作成し、そのコンテンツを以下のように置き換えます。
<UXML xmlns="UnityEngine.UIElements" xmlns:ue="UnityEditor.UIElements">
<Box style="flex-direction: row;">
<Toggle binding-path="enabled" />
<TextField binding-path="name" readonly="true" style="flex-grow: 1;"/>
</Box>
</UXML>
bind-uxml-テンプレート フォルダーに Editor という名前のフォルダーを作成します。
Editor フォルダーで game_switches_editor.uxml という名前の UI ドキュメントを作成し、そのコンテンツを以下のように置き換えます。
<UXML xmlns="UnityEngine.UIElements" xmlns:ue="UnityEditor.UIElements">
<Template name="switch" src="../game_switch.uxml"/>
<Instance template="switch" binding-path="useLocalServer" />
<Instance template="switch" binding-path="showDebugMenu" />
<Instance template="switch" binding-path="showFPSCounter" />
</UXML>
ノート: これはカスタムエディターのメイン UXML ファイルです。各プロパティは Instance の binding-path 属性によって game_switch.uxml のインスタンスにバインドされます。
GameSwitchesAsset のカスタムエディターを登録するスクリプトを作成します。
GameSwitchesEditor.cs という名前の C# スクリプトを作成し、そのコンテンツを以下のように置き換えます。
using UnityEditor;
using UnityEngine;
using UnityEngine.UIElements;
namespace UIToolkitExamples
{
[CustomEditor(typeof(GameSwitchesAsset))]
public class GameSwitchesEditor : Editor
{
[SerializeField]
VisualTreeAsset visualTreeAsset;
public override VisualElement CreateInspectorGUI()
{
return visualTreeAsset.CloneTree();
}
}
}
GameSwitchesEditor.cs の Inspector ウィンドウで、game_switches_editor.uxml ファイルを Visual Tree Asset フィールドに割り当てます。
Assets フォルダーに新しいアセットを作成します。GameSwitchesAsset.useLocalServer、GameSwitchesAsset.showDebugMenu、GameSwitchesAsset.showFPSCounter にバインドするトグルとテキストのフィールドが表示されます。