As it is well known, we can modify the meshInfo
of the textInfo
property of TextMeshPro’s TMP_Text
to change properties like vertex colors of existing meshes. For example, the following code snippet:
Button button;
TMP_Text tmp;
void Awake() {
button = GetComponent<Button>();
button.onClick.AddListener(CreateText);
tmp = new GameObject("TMP_Text").AddComponent<TextMeshProUGUI>();
tmp.transform.SetParent(FindObjectOfType<Canvas>().transform);
}
void CreateText() {
tmp.SetText("This is a test sentence");
tmp.ForceMeshUpdate();
TMP_TextInfo textInfo = tmp.textInfo;
TMP_MeshInfo[] meshInfos = tmp.textInfo.meshInfo;
foreach (var info in meshInfos) {
for (int index = 0; index < info.colors32.Length; index++) {
info.colors32[index] = new Color32(255, 0, 0, 255);
}
}
tmp.UpdateVertexData(TMP_VertexDataUpdateFlags.Colors32);
}
This allows us to set the text to be displayed and modify the text to appear in red color after clicking a button, and then refresh it on the canvas.
However, I’m currently facing an issue where if I place the creation of the TMP_Text
and the code to modify the mesh within the same frame, the changes to the mesh get reverted. For instance:
Button button;
void Awake() {
button = GetComponent<Button>();
button.onClick.AddListener(CreateText);
}
void CreateText() {
TMP_Text tmp = new GameObject("TMP_Text").AddComponent<TextMeshProUGUI>();
tmp.transform.SetParent(FindObjectOfType<Canvas>().transform);
tmp.SetText("This is a test sentence");
tmp.ForceMeshUpdate();
TMP_TextInfo textInfo = tmp.textInfo;
TMP_MeshInfo[] meshInfos = tmp.textInfo.meshInfo;
foreach (var info in meshInfos) {
for (int index = 0; index < info.colors32.Length; index++) {
info.colors32[index] = new Color32(255, 0, 0, 255);
}
}
tmp.UpdateVertexData(TMP_VertexDataUpdateFlags.Colors32);
}
While debugging with breakpoints, I’ve confirmed that meshInfo.colors32
is indeed being modified. But as the execution continues, at some point, meshInfo.colors32
seems to revert back to its original state (the TextMeshPro codebase is quite extensive, and I don’t have the capacity to identify the exact issue). My only assumption is that there might be a refresh operation on meshInfo
at the end of the frame after the creation of TMP_Text
, causing the reset.
Is there any way I can prevent this reset from happening or, in other words, what approach should I take to immediately modify meshInfo
in the same frame in which TMP_Text
is created?