Text Mesh Pro Garbage Collection

I am working on a game that we can hit multiple enemies. When enemies got hit by player Damage Texts are showing up above enemies. I have a basic pool system for this Text’s. Setting Text’s like this causing so much Garbage Collection. How can I avoid this?


Take a look at my post on this thread: Why do strings create garbage? page-2#post-9195335

1 Like

The short version is that you need to have the text as a character array and use TMP_Text.SetCharArray(char[ ], int, int).

https://docs.unity3d.com/Packages/com.unity.textmeshpro@3.0/api/TMPro.TMP_Text.html?q="setchararray"#TMPro_TMP_Text_SetCharArray_System_Char___System_Int32_System_Int32_

My post covers how to build a dynamic string, including appending the value of number variables, as a character array without ever allocating any garbage, as strings are known to do. Then, setting that character array to your text component with SetCharArray, but first checking to see whether the text has changed to avoid unnecessary recalculation of the text geometry if the text is the same. Full code examples for every method out there that I know of are included.

1 Like

Also, when you remove a text component from the front of the list, the List class has to copy all of the other text elements in its internal array over by one. If you remove from the end it avoids copying anything. It can just pop the last element off the array, so it’s a bit more efficient behind the scenes.

public TextMeshPro Get(char[] text, int start, int length, Vector3 position, Color color)
{
    TextMeshPro tempText = null;
    int last = _damageTextList.Count - 1;
    if(last >= 0)
    {
        tempText = _damageTextList[last];
        _damageTextList.RemoveAt(last);
        tempText.SetCharArray(text, start, length);
        tempText.transform.position = position;
        tempText.color = color;
        tempText.gameObject.SetActive(true);
    }
    return tempText;
}
1 Like

Thank you for your time man. I hope this is gonna solve my problem. Thank you so much!

1 Like