Set UI Text To "Text: " And A Variable (C#)

Hi guys! Sorry for the dumb question, I’m new with Unity and I couldn’t find how to do this after a Google search.

Here is the code I use:

private Text textRef;

    void Start () {
        textRef = GetComponent <Text> ();
    }

    void Update () {
        float Speed = 100f;
        textRef.text = Speed;

I want to set “textRef.text” to Speed (var) and “km/h”

Thanks in advance for the answers! =D

textRef.text = "Speed " + Speed.ToString() + " km/h";

That will do it, although you may want to use an int unless you what decimal places as well.

1 Like

@WarmedxMints_1 's code will do the trick, but here are a few more options.

One, float.ToString can accept a parameter that defines the format of the data to be used.

textRef.text = Speed.ToString("#.00");

^ will show you 2 decimal places

It supports a ridiculous amount of options, though 99% of the time I find that the “#.00” type of option handles what I need.

Two, a good habit to get into is to use string.Format rather than concatenation (the plus sign, when used with strings). The reason being is that the way + works is to make two strings, then make a third string representing the combined value - the first two strings are tossed into the breeze as ‘garbage’ in memory, to eventually be collected by the garbage collector, which is one of the ways that noticeable stutters in framerates happen, so you want to minimize garbage when you can. If you have a longer string being built with a bunch of parts, it has to do this repeatedly, creating tons of little bits of garbage.

…anyway, string.Format basically has you put {0} {1} {2} into a string, then replaces them with the parameters you give it after that - {0} replaced with the first, {1} with the second, etc.

textRef.text = string.Format("{0} km/h", Speed);

(Sidenote: Debug has LogFormat, LogWarningFormat, and LogErrorFormat that work the same way.)

And it actually supports parameters in ToString pretty conveniently, combining the above pieces of advice. It looks like this:

textRef.text = string.Format("{0:#.00} km/h", Speed);
1 Like

Thank you!

Good to know, thank you!

Edit: Hi, when the “Speed” value is 0, the text shows “.00 km/h”. How can I make it keep the 0 at the beginning?

string concatenation on 1 line, such as : string s = a + b + c; (where a, b, c are all strings)
does not produce garbage/intermediate strings. Just for the record.
If you do a lot of those, in a loop say, then a string builder is preferable, of course. :slight_smile:

There’s also a simple numeric formatter like : speed.ToString("N2"); which does 2 places.

1 Like

Speed.ToString(“F2”); would also display 2 places. There are so many ways to do this.

1 Like