Can I measure the size of text without render it?

I’d like to find a way to tell the size of text in pixel unit. The method I’m using is:

  1. Create a shadow TextMeshProUGUI component somewhere and hide it.
  2. Copy the properties of a showing TextMeshProUGUI component to the shadow.
  3. Set the text I was going to measure to the shadow. Call ForceMeshUpdate on it and then get the result by GetRenderedValues.

Basically it’s working in this way but I’m not sure if there were some better approachs since the ForceMeshUpdate seems to be a bit heavier. No need to be very precisely an approximate value would be acceptable.

TMP_Text has a method called GetPreferredValues() that does what I think you want.

I tried the GetPreferredValues() but it will returns a different value from GetRenderedValues() if the text contains spaces.

…if the text contains any spaces, or only if there’s leading/trailing whitespace at the start/end of the string?

The spaces were between in words.