Sign in

Make clickable links in Unity TextMeshPro

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));
}

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.