Unityのゲーム画面にテキストを表示し、スクリプトから操作する方法を説明します。なお、プログラムからUIオブジェクトを生成してレイアウトを作成するにはUIElementsを使うとよいようですが、ひとまずここでは簡易的な方法として、UnityのGUI画面上からUIオブジェクトを配置していきます。
開発環境
- Unity 2019.4.1f1
目次
Text UIオブジェクトを配置する
まずは、UnityのGUI画面からUIオブジェクトのTextを選択して、配置してみましょう。

UI要素はCanvasの子オブジェクトとして配置されます。Canvasについては以下の記事をご覧ください。
あわせて読みたい


Canvasの基本的な設定と使い方【Unity】
UnityのCanvasはゲーム画面にGUIを表示させるためのもので、このCanvasの子オブジェクトとしてGUI要素が配置されます。ここでは、Canvasの基本的な設定について説明して...
スクリプトとText UIオブジェクトを連携させる
ゲーム全体を管理する空(カラ)のGameObjectに以下のスクリプトをアタッチさせます。
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class Manager : MonoBehaviour
{
public Text textUI;
// Start is called before the first frame update
void Start()
{
textUI.text = "Sample Text";
}
// Update is called once per frame
void Update()
{
}
}
スクリプトの中にpublicフィールドを配置すると、Inspector上でも以下のようにそのスクリプトがアタッチされたGameObjectにpublicフィールドが表示されるようになります。

このText UIにHierarchy上のリンクさせたいText UIオブジェクトをドラッグ・アンド・ドロップすることで、スクリプト上のpublicフィールドに設定したText UIオブジェクトがHierarchy上のTextとリンクするようになります。
ゲームを実行すると、以下のようにスクリプトで設定した「Sample Text」という文字列が表示されました。

これで、スクリプト上からText UIオブジェクトの文字を操作することができるようになりました。
コメント