Home > Enterprise >  How to detect clicks on a dynamically updated TextMeshProUI text?
How to detect clicks on a dynamically updated TextMeshProUI text?

Time:04-04

I'm trying to implement a functionality that can determine which word in the text the user clicked on. To do this, I use the TextMeshProUGUI element and the following code:

using System.Collections; using System.Collections.Generic; using UnityEngine; using TMPro;

public class ExtraWordsDefinition : MonoBehaviour { 

public TextMeshProUGUI text;

public string LastClickedWord;

void Start()
{
    text = GetComponent<TextMeshProUGUI>();
}

private void Update()
{
    if (Input.GetMouseButtonDown(0))
    {
        var wordIndex = TMP_TextUtilities.FindIntersectingWord(text, Input.mousePosition, null);

        if (wordIndex != -1)
        {
            LastClickedWord = text.textInfo.wordInfo[wordIndex].GetWord();

            Debug.Log("Clicked on "   LastClickedWord);
        }
    }
}

}`

This code works fine if the text in the element is static (i.e.the text that I specified in the component's settings in the Unity inspector) then the words I click on are displayed in the console.

But, if I try to change the text of the component dynamically through the code, then the script stops detecting clicks on the text at all (the if condition does not work). Also, this way of changing text resets the text alignment settings.

At first I made code where the text was changed by assigning a new string to the ".text" property, but I also tried changing the text through the SetText() method, but that didn't change anything. Unfortunately, searching the internet didn't help me find an answer either.

Please help me figure out what is the reason.

CodePudding user response:

First, I would add logs to verify that the mouse Vector and the TextMesh Vector are compatible. If that is the case, I would add a print when the test is updated and when the mouse is pressed to verify that the mouse pressing happens after the text has been updated and that the positions are still correct. I would also print the index to see if the text is actually found at the given position or if there is another problem. Also, ensure that nothing has a higher layer order than the text mesh after you change the text.

  • Related