ランタイム UI は、以下の手順で作成してゲームビューに表示できます。
.uxml) を作成します。MonoBehaviours を作成します。以下の簡単なランタイム UI サンプルを使用して、使用を開始してください。例では、シーンにラベル、ボタン、トグル、およびテキストフィールドを追加します。ボタンをクリックすると、Console ウィンドウにメッセージが表示されます。トグルを選択してボタンをクリックすると、ボタンがクリックされた回数が Console ウィンドウに表示されます。テキストフィールドにテキストメッセージを入力すると、Console ウィンドウにメッセージが表示されます。
このガイドは、Unity エディター、UI Toolkit、および C# スクリプトに精通している開発者を対象としています。始める前に、以下の点を理解しておいてください。
この例で作成する完成したファイルは、こちらの GitHub リポジトリにあります。
ラベル、ボタン、トグルを含む UI Document を作成します。UI Builder または UXML で UI コントロールを追加する方法については、UI Toolkit について を参照してください。
Unity エディターで任意のテンプレートを使用してプロジェクトを作成します。
以下のコンテンツの UI Document を SimpleRuntimeUI.uxml という名前で作成します。
<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;">
<ui:Label text="This is a Label" display-tooltip-when-elided="true"/>
<ui:Button text="This is a Button" display-tooltip-when-elided="true" name="button"/>
<ui:Toggle label="Display the counter?" name="toggle"/>
<ui:TextField picking-mode="Ignore" label="Text Field" text="filler text" name="input-message" />
</ui:VisualElement>
</ui:UXML>
サンプルシーン内に UIDocument ゲームオブジェクトを作成し、UI Document をソースアセットとして加えます。
サンプルシーンで GameObject > UI Toolkit > UI Document の順に選択します。この例では、以下を作成します。
UIDocument ゲームオブジェクトを階層で選択し、Project ウィンドウの SimpleRuntimeUI.uxml を Inspector ウィンドウの UI Document コンポーネントの Source Asset フィールドにドラッグします。これで、ソースアセットが作成した UXML ファイルに参照されます。
ロジックを追加するには、MonoBehaviour から派生した C# スクリプトを作成し、UI Document コンポーネントが参照するコントロールにアクセスします。
Unity は、UI Document コンポーネントで OnEnable が呼び出されると、コンポーネントのソース UXML をロードします。ビジュアルツリーが必ず正しくロードされるようにするために、OnEnable メソッド内のコントロールと相互作用するロジックを追加します。
以下のコンテンツの C# スクリプトを SimpleRuntimeUI.cs という名前で作成します。
using UnityEngine;
using UnityEngine.UIElements;
public class SimpleRuntimeUI : MonoBehaviour
{
private Button _button;
private Toggle _toggle;
private int _clickCount;
//Add logic that interacts with the UI controls in the `OnEnable` methods
private void OnEnable()
{
// The UXML is already instantiated by the UIDocument component
var uiDocument = GetComponent<UIDocument>();
_button = uiDocument.rootVisualElement.Q("button") as Button;
_toggle = uiDocument.rootVisualElement.Q("toggle") as Toggle;
_button.RegisterCallback<ClickEvent>(PrintClickMessage);
var _inputFields = uiDocument.rootVisualElement.Q("input-message");
_inputFields.RegisterCallback<ChangeEvent<string>>(InputMessage);
}
private void OnDisable()
{
_button.UnregisterCallback<ClickEvent>(PrintClickMessage);
}
private void PrintClickMessage(ClickEvent evt)
{
++_clickCount;
Debug.Log($"{"button"} was clicked!" +
(_toggle.value ? " Count: " + _clickCount : ""));
}
public static void InputMessage(ChangeEvent<string> evt)
{
Debug.Log($"{evt.newValue} -> {evt.target}");
}
}
SimpleRuntimeUI.cs を UIDocument ゲームオブジェクトのコンポーネントとして追加します。