Unity(ver:2022.3.11f1)で、でInputFieldを用いてテキストを入力します。作成したプロジェクト「InputFieldTest」では、ゲームオブジェクト「Button」を押下時にゲームオブジェクト「InputField」に入力されたテキストをコンソールに表示します。作成するスクリプトは表示されているゲームオブジェクト「Cylinder」に設定します。
ゲーム画面の作成
作成したゲーム画面を次に示します。
ゲームオブジェクト「Cylinder」は次のように作成します。
ゲームオブジェクト「InputField」「Button」は次のように作成します。
ゲームオブジェクトの配置
各ゲームオブジェクトの配置はInspectorで次のように設定しました。
InputFieldの設定
ゲームオブジェクト「InputField」に次のように入力制限を書けます。
- 英数字のみを入力
- 文字数の制限
「Content Type」:「Alphanumeric」
「CharacterLimit」:制限文字数。「0」は無制限です。
スクリプトの作成
作成するスクリプトでは、ゲームオブジェクト「Button」のクリックイベントを受けて、ゲームオブジェクト「InputField」に入力されている英数字のテキストをConsoleに表示します。
Unityのスクリプトテンプレートを次のように作成します。
- GameObject.Findメソッドのパラメータにゲームオブジェクト名(Cylinder1…等)を設定し、対応するゲームオブジェクトインスタンスを取得します。
- ボタンの20行目でイベントリスナーを登録します。
- 29行目でイベント処理を行います。
InputFieldTest\NewBehaviourScript.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using TMPro;
public class NewBehaviourScript : MonoBehaviour
{
// Start is called before the first frame update
TMP_InputField inputField;
GameObject cylinder;
GameObject button;
void Start()
{
cylinder = GameObject.Find("Cylinder1");
//cylinder.transform.Translate(0.5f, 2.5f, 0.0f);
inputField = GameObject.Find("InputField (TMP)1").GetComponent<TMP_InputField>();
button = GameObject.Find("Button1");
button.GetComponent<Button>().onClick.AddListener(ButtonClick);
}
// Update is called once per frame
void Update()
{
}
public void ButtonClick()
{
UnityEngine.Debug.LogWarning("ButtonClick: ");
string str = inputField.text;
UnityEngine.Debug.LogWarning(str);
}
}
Unityの実行
ゲームをプレーすると次のようにゲーム画面が表示され、ゲームオブジェクト「InputField」に英数字を入力してゲームオブジェクト「Button」を押下すると、ゲームオブジェクト「InputField」に入力されたテキストが、Consoleに表示されます。
Consoleの表示を見るとボタン押下のイベントが2回発生しています。Inspectorの「OnClick」でイベント処理を登録するとイベントは1回表示します(正常動作)。なぜスクリプトでのイベント処理の登録で、イベントが2回発生するのか、原因不明。







