LoginSignup
3
0

More than 1 year has passed since last update.

【Unity】TextMeshProの値をC#で変更する方法

Posted at

TextMeshProの値をC#スクリプトから設定や変更を行う手順を説明する
今回は、ボタンが押された回数を表示するTextMeshProを作成する

TextMeshProとButtonを作成する

  1. HierarchyビューでTextMeshProとButtonを追加
    image.png
  2. 位置やサイズを調節
    image.png

C#スクリプトを作成する

  1. ProjectビューでC# Scriptを好きなフォルダに作成する
    image.png
  2. 作成したC#ファイルを開く
  3. ボタンが押されたときに呼び出す関数を作成する
    1. usingの追加
      TextMeshProのクラスを使用するために下記のusingをファイルの先頭に追加
      using TMPro;
      
    2. 変数・オブジェクトの宣言
      //ボタンが押された回数
      private int count = 0;
      //TextMeshProのオブジェクト
      public TextMeshProUGUI countText;
      
    3. 関数の作成
      public void PushButton()
      {
          count++;
          countText.text = "Score:" + count;
      }
      

C#スクリプトが完成

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using TMPro;

public class UpdateText : MonoBehaviour
{
    //ボタンが押された回数
    private int count = 0;
    //TextMeshProのオブジェクト
    public TextMeshProUGUI countText;

    public void PushButton()
    {
        count++;
        countText.text = "Score:" + count;
    }
}

作成したスクリプトをオブジェクトに適用する

  1. Hierarchyビューで空のGameObjectを作成する
    image.png
  2. ProjectビューのC#スクリプトをGameObjectにドラッグ&ドロップ
  3. HierarchyビューのGameObjectをクリックして、Inspectorビューに作成したスクリプトが適用されているか確認
    image.png
  4. Inspectorビューで表示しているGameObjectの[Update Text]-[Count Text]に値を変更するTextMeshProをドラッグ&ドロップ
  5. ProjectビューでButtonをクリックして、Inspectorビューを表示する
  6. On Click ()のObjectにスクリプトを適用したGameObjectをドラッグ&ドロップ
    image.png
  7. Functionに作成した関数を指定する
    image.png

実行してみる

gif.gif

3
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
3
0