0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

【unity】画面上のテキストをスクリプトで操作する

Posted at

はじめに

敵のHPやスコアのような、動的なテキストを画面上に表示したかったので、メモ。

内容

オブジェクトとして追加したText(TextMeshPro)の値をいじればよい。
例として、敵のHPを表示するコードを載せる。

テキストの値の編集
    // テキストエリア
    public TextMeshProUGUI hpText;

    void Update()
    {
        string dispTextArea = "";

        dispTextArea += String.Format(
            "{0}: {1}/{2}",
            objName,
            Math.Ceiling(hp),
            hpMax
            );

        // テキストエリアを画面にセット
        hpText.text = dispTextArea;
    }

TextMeshProUGUI型の変数に表示させたいTMPを割り当てる。
その後、TMPのtextに、表示させたいテキストを代入する。

詳細

        dispTextArea += String.Format(
            "{0}: {1}/{2}",
            objName,
            Math.Ceiling(hp),
            hpMax
            );

今回の例では、String.Format([text], [value1], ...)を用いている。

[text]の中で変更させたい部分に{0}{1}をあらかじめ入力しておき、String.Format()にて{0}の部分に表示させたい値を引数で指定させてやると、その部分に値が表示される。

まとめ

テキストを動的に変更させること自体は単純なので、今回はString.Format()を使用して実装してみた。
今後表示させたいテキストの量が増えた際の対応も今後考えてみることとする。

参考文献

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?