简体   繁体   中英

How to detect clicks on a dynamically updated TextMeshProUI text?

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 (iethe 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 inte.net didn't help me find an answer either.

Please help me figure out what is the reason.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM