Display numbers in UI.Text Garbage Free?

Hi!

I’ve been reading a lot of forums and discussions in regards to converting a number to string garbage free.

At the moment any of my attempts to display a number in a UI.Text text created garbage, so this triggered the Garbage Collector and I get some performance hiccups on mobile when that happens.

Basically, I want to display the number of coins the player collected and sometimes he can collect more of them in quick succession. That is when the hiccups occur.

Basically:

myUIText.text = myIntValue.ToString();

Generates garbage.

Using StringBuilder is no good either, because this one generates garbage when converting ToString()

A popular fix is generating all the strings before hand and just placing those in the UI.Text.text field.

string[] allNumbers = new string[100] {"1", "2", .... etc};

myUIText.text = allNumbers[myIntValue];

But this is not good when you have a big range of numbers.

I saw some other clever tries to fix this, but some of them are obsolete nowadays for some reason.

Is there any way to display a number in UI.Text without garbage being generated?

I don’t know how you’d turn a number into a string without garbage when you’re one format into another, which by default, because there is no explicit function for it, will create garbage.

It’s the easiest to implicitly convert numbers into strings, like this:

int number = 13;

string Sentence = "John has " + number + " apples";

It will print John has 13 apples.

Trying to optimize the above is microoptimization and even though it is useless, it is also bad to try and make something good better risking to break a lot of stuff. I don’t thing there is a single way to convert any number into a string without generating garbage besides caching which is a huge memory hog. Stick to the basics.

I can’t see the .ToString() method to be your sole reason for hiccups. You should use the profiler during game testing to see what scripts and methods are called during spiking.

Many games—mine included—have a plethora of text generated/appearing every frame, so it’s weird for that to be an issue. It can, however, be how you’re displaying the text…