I am currently converting some code to use TextMeshPro.SetText(StringBuilder) instead of TextMeshPro.text to try and reduce runtime garbage generation. While doing this I have found that GetTextInfo() has started to to have side effects when used after SetText(StringBuilder), but it didn’t when using the text property. I suspect this is a bug.
The following is a simplified example:
This results in “A” being displayed:
StringBuilder text = new StringBuilder();
text.Append("A");
TextMeshPro textMeshPro = gameObject.AddComponent<TextMeshPro>();
textMeshPro.text = text.ToString();
textMeshPro.GetTextInfo("B");
This results in “B” being displayed:
StringBuilder text = new StringBuilder();
text.Append("A");
TextMeshPro textMeshPro = gameObject.AddComponent<TextMeshPro>();
textMeshPro.SetText(text);
textMeshPro.GetTextInfo("B");
I am using Unity3D 2019.4.16f1 and TextMeshPro 2.1.1 .
Since I made significant changes related to internal text backing buffers in the latest release of the TMP package, I suggest you give the latest release a try. The latest for Unity 2019.4 is version 2.1.4.
I have just re-tested against the latest LTS versions Unity 2019.4.21f1 & 2.1.4, and I can confirm that the behavior has now changed from the older versions I was originally using.
Both code snippets from above result in “B” being displayed. i.e. using GetTextInfo() causes the current text value to be updated. Everything seems to be more consistent, both approaches act in the same way now, and the text shown in the inspector window always matches the in scene text (it wasn’t before when using the SetText() version). However, I guess this isn’t what I was expecting? I thought GetTextInfo() could be used to evaluate the length of a text string without modifying the current value. If not, is there a way to do that properly?
A StringBuilder overload of GetTextInfo()/GetPreferredValues() would be nice.
I am not sure if I am missing something here, but as of Unity 2019.4.21f1 & 2.1.4, using GetPreferredValues() will result in the text being overwritten (using either .text or SetText()). The behavior of GetPreferredValues() seems about the same as GetTextInfo().
e.g.
StringBuilder text = new StringBuilder();
text.Append("A");
TextMeshPro textMeshPro = gameObject.AddComponent<TextMeshPro>();
textMeshPro.text = text.ToString();
textMeshPro.GetPreferredValues("B");
// B gets displayed