バージョン: 2023.2 以降
この例では、カスタムエディターウィンドウでバインド可能なカスタムコントロールを作成する方法を説明します。
この例では、double データ型のプロパティにバインドされるカスタムコントロールを作成します。この例は、文字列や整数など、他のデータ型のプロパティにバインドするように変更することができます。
この例で作成して完成したファイルは、この GitHub リポジトリ にあります。
このガイドは、Unity エディター、UI Toolkit、および C# スクリプトに精通している開発者を対象としています。始める前に、以下の点を理解しておいてください。
カスタムコントロールを定義する C# クラスを作成します。
ExampleField という名前のフォルダーを作成します。ExampleField フォルダーに ExampleField.cs という名前の C# スクリプトを作成してから、そのコンテンツを以下に置き換えます。using UnityEngine.UIElements;
namespace UIToolkitExamples
{
// ExampleField inherits from BaseField with the double type. ExampleField's underlying value, then, is a double.
[UxmlElement]
public partial class ExampleField : BaseField<double>
{
Label m_Input;
// Default constructor is required for compatibility with UXML factory
public ExampleField() : this(null)
{
}
// Main constructor accepts label parameter to mimic BaseField constructor.
// Second argument to base constructor is the input element, the one that displays the value this field is
// bound to.
public ExampleField(string label) : base(label, new Label() { })
{
// This is the input element instantiated for the base constructor.
m_Input = this.Q<Label>(className: inputUssClassName);
}
// SetValueWithoutNotify needs to be overridden by calling the base version and then making a change to the
// underlying value be reflected in the input element.
public override void SetValueWithoutNotify(double newValue)
{
base.SetValueWithoutNotify(newValue);
m_Input.text = value.ToString("N");
}
}
}
ExampleField フォルダーに ExampleField.uxml という名前の UI Document を作成します。ExampleField.uxml を開き、そのコンテンツを以下に置き換えます。<ui:UXML xmlns:ui="UnityEngine.UIElements" xmlns:example="UIToolkitExamples">
<example:ExampleField label="Binding Target" binding-path="m_Value" />
</ui:UXML>
ExampleField.uxml をダブルクリックして UI Builder で開きます。ExampleField が Hierarchy ウィンドウに表示され、Viewport に可視化されます。Hierarchy ウィンドウで ExampleField を選択すると、Binding Path ボックスと Label ボックスに割り当てられた値が Inspector ウィンドウに表示されます。ExampleField フォルダーに ExampleFieldComponent.cs という名の C# スクリプトを作成してから、そのコンテンツを以下に置き換えます。using UnityEngine;
namespace UIToolkitExamples
{
public class ExampleFieldComponent : MonoBehaviour
{
[SerializeField]
double m_Value;
}
}
ExampleField フォルダーに Editor という名前のフォルダーを作成します。Editor フォルダーに ExampleFieldCustomEditor.cs という名の C# スクリプトを作成してから、そのコンテンツを以下に置き換えます。using UnityEditor;
using UnityEngine.UIElements;
using UnityEngine;
namespace UIToolkitExamples
{
[CustomEditor(typeof(ExampleFieldComponent))]
public class ExampleFieldCustomEditor : Editor
{
[SerializeField]
VisualTreeAsset m_Uxml;
public override VisualElement CreateInspectorGUI()
{
var parent = new VisualElement();
m_Uxml?.CloneTree(parent);
return parent;
}
}
}
ExampleFieldCustomEditor.cs を選択します。ExampleField.uxml を Inspector ウィンドウの Uxml ボックスにドラッグします。ExampleFieldComponent コンポーネントをゲームオブジェクトに加えます。カスタムコントロールが Inspector に表示されます。Binding Target のデフォルト値 0 が表示されます。基礎となる double プロパティの値を変更すると、UI にその変更が反映されます。