Unity highlighting words in a TextMeshPro element on click

I am making a text scenario based game and I want to give the option for the user to click words and highlight them in the text scenario but I am not sure how to do this.

I have added links into my text scenario, I then use OnPointerClick method to highlight the corresponding part of scenario by editing the text and adding <mark=#somecolorcode> to highlight it. However this means hardcoding in the <mark> tag and it doesn't work when trying to highlight multiple words.

So assume I have a sample text: "This is <link=some>some sample text for <link=testing>testing".

public class ClickText : MonoBehaviour, IPointerClickHandler
{
   public void OnPointerClick(PointerEventData eventData)
   {
       var text = GetComponent<TextMeshProUGUI>();
       if(eventData.button == PointerEventData.InputButton.Left)
       {
           int linkIndex = TMP_TextUtilities.FindIntersectingLink(text, Input.mousePosition,null);
           if(linkIndex > -1)//check actually clicked on something we want clicked
           {
               var linkInfo = text.textInfo.linkInfo[linkIndex];
               var linkId = linkInfo.GetLinkID();

               if (linkId == "some") //highlight word some
               { 
                   text.text = "This is <link=some><mark=#FF00FF80>some</mark></link> 
                                sample text for <link=testing>testing</link>";
               }
               if (linkId == "testing") //highlight word testing
               { 
                   text.text = "This is <link=some>some</mark></link> sample text 
                                for <link=testing><mark=#FF00FF80>testing</mark></link>";
               }
           }
       }
    }
}

If the user clicks some and then testing then some will become unhighlighted because of the hardcoding, is there a way to insert code into a TextMeshPro element without ovwerwriting the whole thing or is there another way to do what I am trying to achieve?

1 answer

How many English words
do you know?
Test your English vocabulary size, and measure
how many words do you know
Online Test
Powered by Examplum