Search Unity

  1. Unity support for visionOS is now available. Learn more in our blog post.
    Dismiss Notice

Question Text Mesh Pro Garbage Collection

Discussion in 'UGUI & TextMesh Pro' started by berkuslu97, Sep 28, 2023.

  1. berkuslu97

    berkuslu97

    Joined:
    Jun 30, 2018
    Posts:
    22
    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?


    upload_2023-9-29_0-45-10.png
    upload_2023-9-29_0-45-30.png
     
  2. CodeRonnie

    CodeRonnie

    Joined:
    Oct 2, 2015
    Posts:
    521
  3. CodeRonnie

    CodeRonnie

    Joined:
    Oct 2, 2015
    Posts:
    521
    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/c...rray_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.
     
    Last edited: Sep 29, 2023
    berkuslu97 likes this.
  4. CodeRonnie

    CodeRonnie

    Joined:
    Oct 2, 2015
    Posts:
    521
    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.
    Code (CSharp):
    1. public TextMeshPro Get(char[] text, int start, int length, Vector3 position, Color color)
    2. {
    3.     TextMeshPro tempText = null;
    4.     int last = _damageTextList.Count - 1;
    5.     if(last >= 0)
    6.     {
    7.         tempText = _damageTextList[last];
    8.         _damageTextList.RemoveAt(last);
    9.         tempText.SetCharArray(text, start, length);
    10.         tempText.transform.position = position;
    11.         tempText.color = color;
    12.         tempText.gameObject.SetActive(true);
    13.     }
    14.     return tempText;
    15. }
     
    berkuslu97 likes this.
  5. berkuslu97

    berkuslu97

    Joined:
    Jun 30, 2018
    Posts:
    22
    CodeRonnie likes this.