【Unity】TextMeshにカウントアップを表示する


やったこと

  • 3D空間にText Meshを使って、テキストを表示
  • 秒でカウントアップ
  • ある秒数に達したら、"FINISH"を表示

前提

  • UnityがPCに入っている かつ ビルドできるようになっている

作る

TextMeshを作成する
  • 左ペインで右クリックメニューを選択し、空のObjectを作成する(Create Empty)

  • 空のObjectのInspectorでText MeshをAdd Componentする(textで検索するとすぐ見つかる)

  • Textに初期表示の"TIME"を入れる(Font Sizeを大きくしておくと、文字がにじまない)

  • Sceneに"TIME"というText Meshが表示される

Scriptを書く
  • Assetsの下で右クリックし、Create<C# Scriptを選択

  • コードを書く

    C#
    using System.Collections;
    using System.Collections.Generic;
    using UnityEngine;
    public class MeasureTime : MonoBehaviour {
    GameObject time;
    int timeLimit;
    float deltaTime;
    int intNowTime;
    string strNowTime;
    // Use this for initialization
    void Start () {
        Debug.Log(":::::START:::::");
        time = GameObject.Find("Time");   // 時間計測用GameObjectの取得
        timeLimit = 10;   // 制限時間
    }
    // Update is called once per frame
    void Update () {
        deltaTime += Time.deltaTime;   // 経過時間
        intNowTime = (int)deltaTime;   // 経過時間の整数部分
        timeLimit = timeLimit - intNowTime;   // 実際の秒数
        strNowTime = intNowTime.ToString();   // TextMeshGameObjectに代入するためにString型にする
        time.GetComponent<TextMesh> ().text = strNowTime;
        // 制限時間経過時の設定
        if(intNowTime > 10){
            time.GetComponent<TextMesh> ().text = ":::::FINISH:::::";
        }
    }
    }
    
ScriptをText Meshにアタッチする
  • Assetsの下のC#のファイルをHierarchyのObjectにdrag & dropする