Search Unity

Allocation-free way of showing numbers in the UI using TextMesh Pro

Discussion in 'Community Learning & Teaching' started by yasirkula, Sep 4, 2019.

  1. yasirkula

    yasirkula

    Joined:
    Aug 1, 2011
    Posts:
    2,879
    Hello,

    Basically, calling
    textObject.text = "" + 12345;
    (or
    textObject.text = 12345.ToString();
    ) will result in a small allocation. If the text changes frequently, this might trigger the garbage collector (GC).

    Today, I saw the SetCharArray function of the TextMesh Pro text objects and decided to implement some extension functions that fill a char array with the digits of an integer. Then, this array is passed to the SetCharArray function. This results in no allocations.

    Available at: https://gist.github.com/yasirkula/31704321d6eef8df19933fe502ae6219

    After importing the script to your project, you can simply call
    textObject.SetText( 12345 );
    . Be aware that Profiler will show some GC while testing on the Editor but there is no GC in a build.

    P.S. Now supports float and doubles, as well!

    Enjoy!
     
    Last edited: Jan 29, 2021