Display numbers w/o allocations

I’m trying to use unity’s GUI text tool to display a few numbers on the screen (numbers change every fixedupdate), but it only seems to take a string, not an integer, which causes allocations every fixedupdate. I’m looking to avoid this, if possible. Any feedback is welcome.

Text takes a string. There is no way around this. If you have an int, you convert it into a string and assign it to the text of the gui.

I suppose you could do some math to figure out what number was in each position of the int and instead of displaying a string, display images and change out sprites to match the numbers, but unless you’ve profiled and noticed some issues with converting to a string, it may not be worth the trouble.

I’m more just trying to avoid the garbage collector all together. Unless it’s normal for games to have the garbage collector run frequently every 30-60 seconds?

If your numbers are relatively low, then it is possible to store all of the strings beforehand. You’re trading memory for possible CPU. Only do this if you don’t have numbers in the millions and if you think GC is hindering your performance on the target device and you have some spare memory. The mentioned image-showing after divisions is memory-friendly, you’re giving up CPU resource for… avoiding CPU resource usage.

using UnityEngine;
using UnityEngine.UI;

public class NewBehaviourScript : MonoBehaviour
{
    private Text _text;
    private string[] _texts;
    private int _i = 0;
   
    private void Awake()
    {
        _texts = new string[1000];
        for(var i = 0; i < 1000; i++) _texts[i] = i.ToString();
        _text = GetComponent<Text>();
    }

    private void Update()
    {
        _i++;
        if (_i < 1000)
            _text.text = _texts[_i];
    }
}
1 Like