Make clickable links in Unity TextMeshPro

Mopsicus
2 min readJun 4, 2020

How to make links in TMP text clickable? Simple! Everything what you need is open TextMeshPro docs and add some code.

Let’s we have TMP text component with text that contains links, e.g. https://mopsicus.ru, www.unity3d.com. And we need make it looks like this and it will be clickable:

For that, we need find links in text via regular expression, cut them (if need) and modify for TMP format.

// Check links in text 
void CheckLinks () {
Regex regx = new Regex ("((http://|https://|www\\.)([A-Z0-9.-:]{1,})\\.[0-9A-Z?;~&#=\\-_\\./]{2,})" , RegexOptions.IgnoreCase | RegexOptions.Singleline);
MatchCollection matches = regx.Matches (textMessage.text);
foreach (Match match in matches)
textMessage.text = textMessage.text.Replace (match.Value, ShortLink(match.Value));
}
// Cut long url
string ShortLink (string link) {
string text = link;
int left = 9;
int right = 16;
string cut = "...";
if (link.Length > (left + right + cut.Length))
text = string.Format ("{0}{1}{2}", link.Substring (0, left), cut, link.Substring (link.Length - right, right));
return string.Format("<#7f7fe5><u><link=\"{0}\">{1}</link></u></color>", link, text);
}

Read TMP docs to know how to set text underline, color, etc. Last step: set handler for mouse click and define clicked link:

// Get link and open page 
public void OnPointerClick (PointerEventData eventData) {
int linkIndex = TMP_TextUtilities.FindIntersectingLink (textMessage, eventData.position, eventData.pressEventCamera);
if (linkIndex == -1)
return;
TMP_LinkInfo linkInfo = textMessage.textInfo.linkInfo[linkIndex];
string selectedLink = linkInfo.GetLinkID();
if (selectedLink != "") {
Debug.LogFormat ("Open link {0}", selectedLink);
Application.OpenURL (selectedLink);
}
}

Source on Github

This article is translation from my blog: https://mopsicus.ru. I will try to translate and write here more often if you like post as this.

--

--