Hi guys. I have a set of Button objects in a Canvas, each containing a TMPro UGUI element whose contents are changed during runtime. The Button objects have a ContentSizeFitter to adapt to the height of the TMPro. I need to use word wrapping because I have multiple lines of text to be shown.
Here’s my code:
int i = 0;
foreach (var optionString in optionsCollection.options) {
dialogueBubbles[i].optionButtonText.text = optionString;
dialogueBubbles[i].optionButtonText.ForceMeshUpdate(true);
dialogueBubbles[i].optionButton.rectTransform.ForceUpdateRectTransforms();
Debug.Log("Option Button " + i + " height: " + dialogueBubbles[i].optionButton.GetComponent<RectTransform>().rect.height);
Debug.Log("Option Button Text " + i + " height: " + " " + dialogueBubbles[i].optionButtonText.GetComponent<RectTransform>().rect.height);
i++;
}
The problem I’m having is that the height values printed are not updated, despite calling ForceMeshUpdate(). What I see in the console is 0 for the TMPro height and the default values set before running the game for the Buttons. Another anomaly that occurs is that the height of the text box sometimes varies by a fixed amount of padding.
I also tried setting the size of the TMPro object manually with GetPreferredValues(text) but this only works for one line of text, as far as I can see, whereas my text needs to span across multiple lines. This is the version of the code above including GetPreferredValues():
int i = 0;
foreach (var optionString in optionsCollection.options) {
Vector2 textSize = dialogueBubbles[i].optionButtonText.GetPreferredValues(optionString);
dialogueBubbles[i].optionButtonText.text = optionString;
dialogueBubbles[i].optionButton.GetComponent<RectTransform>().sizeDelta = textSize;
dialogueBubbles[i].optionButtonText.ForceMeshUpdate(true);
dialogueBubbles[i].optionButton.rectTransform.ForceUpdateRectTransforms();
Debug.Log("Option Button " + i + " height: " + dialogueBubbles[i].optionButton.GetComponent<RectTransform>().rect.height);
Debug.Log("Option Button Text " + i + " height: " + " " + dialogueBubbles[i].optionButtonText.GetComponent<RectTransform>().rect.height);
i++;
}
I’d appreciate any help.