0

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.

dv5775
  • 15
  • 2

1 Answers1

0

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.

Dharman
  • 30,962
  • 25
  • 85
  • 135
  • Thanks for your advices! I tried to check all these options, and when I checked the order of the layers, I accidentally found a solution: for some reason, the shift of the TextMesh object along the Z axis (I put TextMesh object behind the canvas and other objects on canvas) solved my problem. I still don’t understand why this worked, so I need to learn the coordinates and positioning of objects in Unity in more detail. In any case, your advice helped me find the problem, thanks! – dv5775 Apr 04 '22 at 10:36