バージョン:2021.3+
この例では、UXML を使ってバインディングを作成してバインディングパスを設定し、C# スクリプトを使って Bind() メソッドを呼び出す方法を示します。
この例では、シーン内のゲームオブジェクトの Name プロパティにバインドする TextField を持つカスタムエディタウィンドウを作成します。
この例で作成する完成したファイルは、こちらの GitHub リポジトリ にあります。
このガイドは、Unity エディター、UI Toolkit、および C# スクリプトに精通している開発者を対象としています。始める前に、以下の点を理解しておいてください。
UXMLでビジュアル要素とバインディングパスを定義する
Unity で任意のテンプレートを使用してプロジェクトを作成します。
Project ウィンドウに、bind-with-uxml-csharp という名前のフォルダーを作成し、すべてのファイルを保存します。
binding_example.uxml という名前の UI Document を作成し、そのコンテンツを以下のように置き換えます。
<UXML xmlns:ui="UnityEngine.UIElements">
<ui:VisualElement name="top-element">
<ui:Label name="top-label" text="UXML-Defined Simple Binding"/>
<ui:TextField name="GameObjectName" label="Name" text="" binding-path="m_Name"/>
</ui:VisualElement>
</UXML>
C# スクリプトでバインディングを作成し、Bind() メソッドを明示的に呼び出します。
Editor という名前のフォルダーを作成します。
Editor フォルダーに、SimpleBindingExampleUXML.cs という名前の C# スクリプトを作成します。
SimpleBindingExampleUXML.cs のコンテンツを以下のように置き換えます。
using UnityEditor;
using UnityEngine;
using UnityEditor.UIElements;
using UnityEngine.UIElements;
namespace UIToolkitExamples
{
public class SimpleBindingExampleUXML : EditorWindow
{
[SerializeField]
VisualTreeAsset visualTree;
[MenuItem("Window/UIToolkitExamples/Simple Binding Example UXML")]
public static void ShowDefaultWindow()
{
var wnd = GetWindow<SimpleBindingExampleUXML>();
wnd.titleContent = new GUIContent("Simple Binding UXML");
}
public void CreateGUI()
{
visualTree.CloneTree(rootVisualElement);
OnSelectionChange();
}
public void OnSelectionChange()
{
GameObject selectedObject = Selection.activeObject as GameObject;
if (selectedObject != null)
{
// Create the SerializedObject from the current selection
SerializedObject so = new SerializedObject(selectedObject);
// Bind it to the root of the hierarchy. It will find the right object to bind to.
rootVisualElement.Bind(so);
}
else
{
// Unbind the object from the actual visual element
rootVisualElement.Unbind();
// Clear the TextField after the binding is removed
var textField = rootVisualElement.Q<TextField>("GameObjectName");
if (textField != null)
{
textField.value = string.Empty;
}
}
}
}
}
Project ウィンドウで SimpleBindingExampleUXML.cs を選択し、Inspector で binding_example.uxml を Visual Tree フィールドにドラッグします。