1
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 5 years have passed since last update.

[Unity初級]文字列と数値で型変換

Last updated at Posted at 2020-04-25

概要

UIのTextにある数字(得点など)を扱いたい。Text上のデータは文字列型なので数値型に変換をする必要がある。
スクリーンショット (144).png

本文


    using System;


    string x = GameObject.Find("Text").GetComponent<Text>().text;
    int y = Convert.ToInt32(x);
    y += 10;
    GameObject.Find("Text").GetComponent<Text>().text = Convert.ToString(y);

まずConvert.ToInt32()で文字列を数値型に変換。必要な変更をしたらConvert.ToString()で数値型から文字列型に変換すればまたTextに戻すことができます。

追記

using System;が抜けてるとエラーになりました。

追記2

別の表記方法

(123).ToString("D4")
(12.3456).ToString("F3")

D4は4桁に足りない分は左から0を埋めていくタイプの整数型
F3は小数点第3位まで表記の固定小数点型

1
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
1
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?