I’ve got some TextMeshProUGUI components that I poll the preferred width from in order to resize their containers. Sometimes these TMP components returns 0 for the preferred width, even if they have text assigned, and have reported a different width earlier, without me changing anything of the TMP settings.
Here’s an example of an inspector where that’s happening. See the Layout properties at the bottom:
1.5.1 for Unity 2018.4.24f1. There’s no layout components anywhere.
I think I found the bug. My code used to do this:
baseSize = textPlateText.GetPreferredValues();
Now it does this:
baseSize = new Vector2(textPlateText.preferredWidth, textPlateText.preferredHeight);
And the bug is gone!
Looking through the TMP code, it seems like GetPreferredValues sets m_isPreferredWidthDirty = false; but it doesn’t actually set m_preferredWidth. So you’ll probably always get this behaviour if you call GetPreferredValues two times in a row.
There’s something really bad going on between GetPreferredWidth, preferredWidth (the getter) and GetPreferredValues.
For testing purposes, replace the TMP_Text.cs file contained in the Global Package Cache\packages\com.unity.textmeshpro@3.0.4\Scripts\Runtime with the attached revised version.
Let me know if that resolves the issue on your end?
Can you make sure the change was not reverted as this should have resolved that behavior as the text is no longer set by GetPreferredValues(string text) and the other overload also using a string.
Do you mean change when you check the .text property?
How are you setting the text?
Can you provide the steps or simple scene / project that would enable me to reproduce this?
I have a similar issue…but with Height…
currentWidth is 155
Font is 24 point
GetPreferred Value return 200.13 => cellSizer.GetPreferredValues(text, currentWidth, 0f).y
If I set text, then look at cellSizer.preferredHeight I get 232.82 which is the proper height.
Not sure it was broken in 3.0.5 (current version installed), but I didn’t notice it in 3.0.4 here is the code
This is what I get in the Editor using the font you provided which is a height of 196.13.
See if you get the correct values testing with the following simply script.
using UnityEngine;
using TMPro;
public class PreferredValueCheck : MonoBehaviour
{
public TextMeshProUGUI TextComponentUI;
private string m_Label_01 = "A few lines of text for testing preferred values.";
private void Awake()
{
Vector2 preferredValues = TextComponentUI.GetPreferredValues(m_Label_01, 155, 0);
Debug.Log(preferredValues.ToString("f2"));
TextComponentUI.text = m_Label_01;
Debug.Log("Width: " + TextComponentUI.preferredWidth + " Height: " + TextComponentUI.preferredHeight);
}
}
Timing on when you are executing your code might be a factor. If you could provide a simple test scene that would be most useful to figure out why you are getting those values.