Search Unity

  1. Megacity Metro Demo now available. Download now.
    Dismiss Notice
  2. Unity support for visionOS is now available. Learn more in our blog post.
    Dismiss Notice

Hyperlinks in Unity.UI Text

Discussion in 'UGUI & TextMesh Pro' started by DanSuperGP, Feb 11, 2015.

  1. DanSuperGP

    DanSuperGP

    Joined:
    Apr 7, 2013
    Posts:
    408
    Has anyone done anything for putting hyperlinks in UI Text?

    I'm working on an account sign up page, and it would be great to be able to hyperlink the Terms of Service and Privacy Policy like most website forms would do.
     
  2. SimonDarksideJ

    SimonDarksideJ

    Joined:
    Jul 3, 2012
    Posts:
    1,688
    Lohoris2 and Ash-Blue like this.
  3. Feaver1968

    Feaver1968

    Joined:
    Nov 16, 2014
    Posts:
    70
    Lohoris2 likes this.
  4. SimonDarksideJ

    SimonDarksideJ

    Joined:
    Jul 3, 2012
    Posts:
    1,688
    I've voted, however @Breyer s solution does work and it seems for a lot of cases UT is happy for the community to provide these kinds of features, especially with the new UI.
    At some point I must add this solution to the UI Extensions bitbucket repo https://bitbucket.org/ddreaper/unity-ui-extensions
     
  5. DanSuperGP

    DanSuperGP

    Joined:
    Apr 7, 2013
    Posts:
    408
    I'd love to vote for it, but my 10 votes were used up long ago...

    stupid system.
     
  6. SimonDarksideJ

    SimonDarksideJ

    Joined:
    Jul 3, 2012
    Posts:
    1,688
    Well, do what I did and reallocate some of your votes :D Based of the likelihood of them fixing some stuff
     
    Lohoris2 likes this.
  7. Feaver1968

    Feaver1968

    Joined:
    Nov 16, 2014
    Posts:
    70
    I haven't been able to get it working. Just get an ArgumentOutOfRangeException.
     
  8. Breyer

    Breyer

    Joined:
    Nov 10, 2012
    Posts:
    412
    @up weird. As far as i remember i havent this error in latest version. Could you post more info? Os, screenshot etc. Anything if you want you could do this there or pm
     
    azeed_unity likes this.
  9. Feaver1968

    Feaver1968

    Joined:
    Nov 16, 2014
    Posts:
    70
    Interactable text over on this thread is the thing I'm talking about. http://forum.unity3d.com/threads/scripts-useful-4-6-scripts-collection.264161/
    SimonDarksideJ was talking about that one I believe.

    1. From a new project in Unity 4.6.2f1 import the package.
    2. Create a Canvas
    3. Create a TextWithEvents & parent it to canvas
    4. Create a Tex Button & parent it to TextWithEvents
    5. paste the text 'if u need link in text type <a href=nameAction>link</a> if u need dynamic color then type classic' into the TextWithEvents Text field
    (error here)

    Also

    1. From a new project in Unity 4.6.2f1.
    2. Copy the separate scripts (TexButtonHandler.cs,TextClassHandler.cs,TextWithEvents.cs,TextButton.cs) from the thread into the project, putting the Editor scripts in an Editor folder.
    3. Create a Canvas
    4. Create a TextWithEvents
    (error here)
     
  10. DanSuperGP

    DanSuperGP

    Joined:
    Apr 7, 2013
    Posts:
    408
    Yeah, I got the same thing. Argument out of range...
     
  11. Breyer

    Breyer

    Joined:
    Nov 10, 2012
    Posts:
    412
    ok i will investigate this tomorrow (bit late there and exam tomorrow). today im too busy. thanks for report
     
    Last edited: Feb 12, 2015
    DanSuperGP likes this.
  12. DanSuperGP

    DanSuperGP

    Joined:
    Apr 7, 2013
    Posts:
    408
    Thanks, good luck on your exam!
     
  13. SimonDarksideJ

    SimonDarksideJ

    Joined:
    Jul 3, 2012
    Posts:
    1,688
    Right, seems the core of the issue @Breyer is the UI Sample project has changed a lot from the beta days. Your lighting scene is still using the old format and has some missing component issues.
    I personally don't get the errors above and the tooltip does appear but the links don't work.

    I have a copy of the old beta project, so if I have time I'll try and engineer it in to the new UI example project.
     
  14. DanSuperGP

    DanSuperGP

    Joined:
    Apr 7, 2013
    Posts:
    408
    So, my co-worker just suggested a brilliant way of making links... which is to make a tiny image with just a row of pixels along the bottom, the rest transparent

    Then you just make that a button... place it under whatever text you want to hyperlink.... The whole clickable area will become a link...

    So simple.
     
  15. Breyer

    Breyer

    Joined:
    Nov 10, 2012
    Posts:
    412
    this is good for inline link, but rescaling gui (in that case text will move and words dont keep position), multiline, replacing text, change text size on runtime might be problem. i already thought about this way and realized that this is too limited (personally). especially if you think about some special effect like curved text. if this fit perfectly your case then you could go and do it
     
  16. DanSuperGP

    DanSuperGP

    Joined:
    Apr 7, 2013
    Posts:
    408
    Yeah, good point.

    It works in my specific case at least since the UI I'm making is fixed aspect ratio
     
  17. Breyer

    Breyer

    Joined:
    Nov 10, 2012
    Posts:
    412
    Ok got it! ;) there unitypackage with fix. this is limited version of Text Action Pro (no anim support, no fade duration, no phase for curve, no example scene due to reaching 2MB limit, but added small documentation from TAPro) + contemporary fix. Simple replace old files with new from this package and everything should work. Ah and use manual adding TextButton only when you accidentally remove exist TextButton. You need only TextWithEvents everything else is semi-automated
     

    Attached Files:

  18. SimonDarksideJ

    SimonDarksideJ

    Joined:
    Jul 3, 2012
    Posts:
    1,688
    Right, will check this out @Breyer
    If I get it working, you ok with this component going in to the UI Extensions bitbucket repo?
     
  19. Breyer

    Breyer

    Joined:
    Nov 10, 2012
    Posts:
    412
    yes
     
    SimonDarksideJ likes this.
  20. Feaver1968

    Feaver1968

    Joined:
    Nov 16, 2014
    Posts:
    70
    The package imports with errors and warnings. I tried commenting out the offending lines of code, but it still wouldn't work.
     
  21. Breyer

    Breyer

    Joined:
    Nov 10, 2012
    Posts:
    412
    are you talking about missing coroutinetweener? i thought this was in public namespace after full release and thats why i didnt include them. I update my previous post with package. As for warning these wont happen on my unity 4.6 except " Coroutine container not configured... did you forget to call Init?" but this is very problematic i tried several times to solve this and never remove this... fortunately this isnt showstopper and happen on editor mostly

    thanks for notice
     
  22. Adam-Mechtley

    Adam-Mechtley

    Administrator

    Joined:
    Feb 5, 2007
    Posts:
    290
    I just noticed this thread as I was searching for something else. As another alternative for anyone interested, I have an Asset Store package that does this and a few other things (e.g., define custom styles and tags).
     
  23. elpuerco63

    elpuerco63

    Joined:
    Jun 26, 2014
    Posts:
    271
    I get this error: `UnityEngine.UI.Graphic.OnFillVBO(System.Collections.Generic.List<UnityEngine.UIVertex>)' is obsolete: `Use OnPopulateMesh instead.'
     
  24. Stephan-B

    Stephan-B

    Joined:
    Feb 23, 2011
    Posts:
    2,269
    Unity made significant changes to their API in Unity 5.2 and renamed or replaced several functions. I believe OnPopulateMesh was actually replaced between Unity 5.2.0 and Unity 5.2.1. So make sure you update to the latest release of Unity 5.2.

    Alternatively, the latest release of TextMesh Pro on the Unity Asset Store also includes support for links. Here is a video covering this feature.

    As per Adam's post above his Asset also offers support for links.
     
    elpuerco63 likes this.
  25. SimonDarksideJ

    SimonDarksideJ

    Joined:
    Jul 3, 2012
    Posts:
    1,688
    Additionally, Unity changed it all again in 5.2.1P+ / 5.3
    The signature for OnPopulateMesh has changed from:
    Code (CSharp):
    1. OnPopulateMesh(Mesh mesh)
    to
    Code (CSharp):
    1. OnPopulateMesh(VertexHelper vh)
    Causing me no end of woes for the UI Extensions project updating "stuff".
    Also since the asset store doesn't support patch releases, I'm guessing it's going to cause UI assets no end of woe
     
    elpuerco63 likes this.
  26. elpuerco63

    elpuerco63

    Joined:
    Jun 26, 2014
    Posts:
    271
    Thanks for the heads up and help guys :)
     
  27. WiS3

    WiS3

    Joined:
    Apr 5, 2014
    Posts:
    12
    I'm also using Breyer script, but, how i can pass a value (int or string) to the button handler?
    I'm trying to implement an Object Link in a chat, like WoW, and i need to pass an id to the Button function.
     
  28. miguelangeltfp

    miguelangeltfp

    Joined:
    Mar 20, 2013
    Posts:
    3
    Hi,
    I get this error too: `UnityEngine.UI.Graphic.OnFillVBO(System.Collections.Generic.List<UnityEngine.UIVertex>)' is obsolete: `Use OnPopulateMesh instead.'

    I don't know hot to fix it.

    Thank you.
     
  29. SimonDarksideJ

    SimonDarksideJ

    Joined:
    Jul 3, 2012
    Posts:
    1,688
    That's simply an effect of the UI API changing between releases.
    Look at the effect components in the UI Extension project (link in sig) to get a feel between the different branches (4.6 -> 5.2 -> 5.3) to see how it has "evolved"
     
  30. stimul

    stimul

    Joined:
    Nov 28, 2013
    Posts:
    11
    Tomer-Barkan likes this.
  31. Stephan-B

    Stephan-B

    Joined:
    Feb 23, 2011
    Posts:
    2,269
    Just in case someone needs this functionality in the short term, both TextMesh Pro and Adam's package linked above offer support for links. Both product are compatible with the Canvas system / UI.

    Here is an example showing support for links in TextMesh Pro as well as interactions with words as well as characters. This is from example scene 06c - Link Example included with the product.

     
  32. Tomer-Barkan

    Tomer-Barkan

    Joined:
    Jul 31, 2012
    Posts:
    150
    +1. This was in NGUI and seems pretty basic to me...
     
    Alex-id likes this.
  33. Rodolfo-Rubens

    Rodolfo-Rubens

    Joined:
    Nov 17, 2012
    Posts:
    1,197
    Sorry to necro.
    Seems like rects over the text gets misaligned in different resolutions, it doesn't matter how you set up its anchors. :(

    +1, we need this, I want to use this in the credits of my game.
     
  34. SimonDarksideJ

    SimonDarksideJ

    Joined:
    Jul 3, 2012
    Posts:
    1,688
    @Rodolfo-Rubens TextMeshPro is now free for all Unity users, so just go grab it.
     
    Ash-Blue likes this.
  35. Akuma-no-Tsubasa

    Akuma-no-Tsubasa

    Joined:
    Nov 13, 2015
    Posts:
    33
    I just tried that tool but the simple linking doesn't work.
    <link="http://www.google.com">Google</link>

    won't deliver any results when you click it.
     
  36. Stephan_B

    Stephan_B

    Joined:
    Feb 26, 2017
    Posts:
    6,595
    The <link> tag is not the same as <a href="url...">Some text</a>

    The <link> tag allows you to define a region of text that you want to potentially interact with.

    Since these interactions can be anything like changing the color of the text, spawning an object or menu or open a link to a web page, you will need to implement the logic / what you want to have happen when you mouse over or click on such a link.

    See the documentation about the link tag here.

    See Example 12a on how you can implement you own link handling.
     
  37. Akuma-no-Tsubasa

    Akuma-no-Tsubasa

    Joined:
    Nov 13, 2015
    Posts:
    33
    I've seen that Doc but it doesn't really help. There's also no "Example 12a". The Link section is Number 10 and only tells you you have some unique ID but not how you interact with it :/
     
  38. Stephan_B

    Stephan_B

    Joined:
    Feb 26, 2017
    Posts:
    6,595
    In the example folder included with TextMesh Pro, there are 25 examples which includes 12 - Link Example and 12a - Text Interactions which include scripts with event handling to interact with characters, words, lines and links.

    Make sure that you are using the latest release of TMP for the appropriate version of Unity. The latest release on the Asset Store or TMP user forum is 1.0.55.xx.0b11 where xx is the Unity version like 56 or 2017.1.

     
  39. nobluff67

    nobluff67

    Joined:
    Nov 3, 2016
    Posts:
    338
    Hi,

    I am spending a ridiculous amount of time struggling with this, please help.

    None of the example have a CLICKABLE link that takes you to a website. I can not even get the code to work correctly as you need several " within the text, e.g.:

    public TextMeshProUGUI infoText1;

    linkDisplay.text = "<a href=\"www.google.com\">Some text</a>"; (I need to escape the " to satisfy the editor.)

    I am obviously doing something wrong, I am convinced its a simple mistake.

    FYI, I am testing via webplayer.
     
  40. Stephan_B

    Stephan_B

    Joined:
    Feb 26, 2017
    Posts:
    6,595
    TextMesh Pro does not have an <a href> tag. A tag that would allow you to achieve something similar is the <link="ID">some text</link> tag. If you look at example 12a and the related scripts. You will see that TMP can return this link ID via an event when you mouse over said link.

    Once get this callback, you can implement whatever functionality desired for this ID. By functionality, I mean you could change the color of the text, change vertices, or in your case make it open a webpage which would make this tag behaves like <a href>.

    The ID in <link="ID"> has to be unique for whatever you wish to implement for it. This is how you can internally on your end identify what should happen when this link is encountered. You could have several <link="SAME ID> in your text, this simply means the same event callback would be called for all those links using the same ID.

    Focusing on understanding Example 12a and the script used to handle the event and registration for receiving those events. Then the rest of your implementation isn't specific to TMP but on how to open a link in Unity via scripting.
     
  41. nobluff67

    nobluff67

    Joined:
    Nov 3, 2016
    Posts:
    338
    Thanks for the quick reply. I appreciate the direction, however I find this method ridiculously complicated if all I want to do is create a clickable link. I think I will rather look at implementing some of the other suggestions in this thread like a button.
     
  42. Stephan_B

    Stephan_B

    Joined:
    Feb 26, 2017
    Posts:
    6,595
    The information I provided you should make it simple for you to modify the event handler to detect a click instead of mouse over. Then at the point, you have to implement the logic to handle this click.

    Although some aspect of this could be simplified, the need for the user to add this logic would remain as assuming I add a new <a href="url">some text</a> tag, what happens when you click the link? Who decides / controls if a window opens or some new object that potentially contains several other ui elements get instantiated and at what size and where? The identifying what link was clicked is the trivial part of this, the logic of what to do when this happens is what the user needs to implement.
     
  43. Streamside7

    Streamside7

    Joined:
    Nov 8, 2013
    Posts:
    9
    Thank you @Stephan-B for being so gracious in your answers. I truly appreciate it when coders like you take the time to explain things.

    I know this is an old thread, but I can't help but think @nobluff67 was hoping for some sort of in-app browser to be invoked. There are web view assets out there, but buyer beware. One of them is excellent for desktop machines, but doesn't support mobile. Another hooks into the built in web browsers on a mobile device, but cannot be used as a mesh.
     
  44. daniel-lee156

    daniel-lee156

    Joined:
    Jan 26, 2016
    Posts:
    5
    Hi there! Thanks for the detailed information. Is there any way to customize the link keyword? Or instead of using word "link" just use hypertext link mark up like <a> </a>?
     
  45. Stephan_B

    Stephan_B

    Joined:
    Feb 26, 2017
    Posts:
    6,595
    The <link> tag is a predefined keyword like all other tags / rich text features. A different tag could be added where instead of using <link="unique ID">Some text</link>, you could use <a="unique ID">Some text</a>, it would not provide any added benefits.
     
  46. monoclesociety

    monoclesociety

    Joined:
    Jan 2, 2013
    Posts:
    8
    Stephan_B,

    Thank you for helping us out! So I do have some open questions if that's okay with you:

    Scene 12a:
    - When I load up the scene, I notice that there is a canvas that has "Text Mesh Pro UGUI" object under it. I'm assuming that the parent doesn't *have* to have a canvas directly attached to it correct? Quick testing shows that it can still fire off the link events even if the TMP Text has a new empty gameObject between the canvas and the Text component.

    - How do you add clicking action on a link exactly? Is this needed for iOS/Android, since hover isn't really possible for us?

    - In the 12a example, my mouse over does debug log info about the link (NEAT!), however, it only happens once for mouse over, if I move the mouse away from the text and back again, it doesn't fire a second time UNLESS--

    - --UNLESS my mouse moves to the second link, then going back to the first one fires off the event again. Do you see a potential problem if you only have one link to show off?
     
  47. monoclesociety

    monoclesociety

    Joined:
    Jan 2, 2013
    Posts:
    8
    Yeah... we're dorks over here. we just built example 12a for iOS and added an image that would change a different color depending on which link was clicked in the demo, and tapping on them works just fine.

    Totally awesome code, very cool example, consider making the example a bit more descriptive?
     
  48. look001

    look001

    Joined:
    Mar 23, 2017
    Posts:
    111
    Hi everyone, I always try to use less assets, so i gave it a try on my own. Here is the code:
    Code (CSharp):
    1. using System.Collections.Generic;
    2. using UnityEngine;
    3. using UnityEngine.EventSystems;
    4. using UnityEngine.UI;
    5.  
    6.  
    7. public class InfoText : Text, IPointerClickHandler
    8. {
    9.     public string[] links = new string[] {
    10.         "https://forum.unity.com/"
    11.     };
    12.  
    13.     readonly UIVertex[] m_TempVerts = new UIVertex[4];
    14.     List<Bounds2D> bounds;
    15.  
    16.     protected override void OnPopulateMesh(VertexHelper toFill)
    17.     {
    18.         if (font == null)
    19.             return;
    20.  
    21.         // We don't care if we the font Texture changes while we are doing our Update.
    22.         // The end result of cachedTextGenerator will be valid for this instance.
    23.         // Otherwise we can get issues like Case 619238.
    24.         m_DisableFontTextureRebuiltCallback = true;
    25.  
    26.         Vector2 extents = rectTransform.rect.size;
    27.  
    28.         // EDIT: remove '[' and ']' indicators and store the range where links are
    29.         List<int> linkRanges = new List<int>();
    30.  
    31.         string text = this.text;
    32.         int removeCount = 0;
    33.         for (int i = 0; i < text.Length; i++)
    34.         {
    35.             char c = text[i];
    36.             if (c == '[' || c == ']')
    37.             {
    38.                 linkRanges.Add(i - removeCount);
    39.                 removeCount++;
    40.             }
    41.         }
    42.         text = text.Replace("[", "").Replace("]", "");
    43.         // END EDIT
    44.  
    45.  
    46.         var settings = GetGenerationSettings(extents);
    47.         cachedTextGenerator.PopulateWithErrors(text, settings, gameObject);
    48.  
    49.         // Apply the offset to the vertices
    50.         IList<UIVertex> verts = cachedTextGenerator.verts;
    51.         float unitsPerPixel = 1 / pixelsPerUnit;
    52.         //Last 4 verts are always a new line... (\n)
    53.         int vertCount = verts.Count - 4;
    54.  
    55.         // We have no verts to process just return (case 1037923)
    56.         if (vertCount <= 0)
    57.         {
    58.             toFill.Clear();
    59.             return;
    60.         }
    61.  
    62.         Vector2 roundingOffset = new Vector2(verts[0].position.x, verts[0].position.y) * unitsPerPixel;
    63.         roundingOffset = PixelAdjustPoint(roundingOffset) - roundingOffset;
    64.         toFill.Clear();
    65.         if (roundingOffset != Vector2.zero)
    66.         {
    67.             for (int i = 0; i < vertCount; ++i)
    68.             {
    69.                 int tempVertsIndex = i & 3;
    70.                 m_TempVerts[tempVertsIndex] = verts[i];
    71.                 m_TempVerts[tempVertsIndex].position *= unitsPerPixel;
    72.                 m_TempVerts[tempVertsIndex].position.x += roundingOffset.x;
    73.                 m_TempVerts[tempVertsIndex].position.y += roundingOffset.y;
    74.                 if (tempVertsIndex == 3)
    75.                     toFill.AddUIVertexQuad(m_TempVerts);
    76.             }
    77.         }
    78.         else
    79.         {
    80.             for (int i = 0; i < vertCount; ++i)
    81.             {
    82.                 int tempVertsIndex = i & 3;
    83.                 m_TempVerts[tempVertsIndex] = verts[i];
    84.                 m_TempVerts[tempVertsIndex].position *= unitsPerPixel;
    85.                 if (tempVertsIndex == 3)
    86.                     toFill.AddUIVertexQuad(m_TempVerts);
    87.             }
    88.         }
    89.  
    90.         m_DisableFontTextureRebuiltCallback = false;
    91.  
    92.  
    93.         // EDIT: Create bounds for clicking
    94.         bounds = new List<Bounds2D>();
    95.  
    96.         for (int i = 0; i < linkRanges.Count; i += 2)
    97.         {
    98.             var charInfoStart = cachedTextGenerator.characters[linkRanges[i]];
    99.             var charInfoEnd = cachedTextGenerator.characters[linkRanges[i + 1]];
    100.  
    101.             var current = new Bounds2D();
    102.  
    103.             var cornerStart = charInfoStart.cursorPos;
    104.             var cornerEnd = new Vector2(charInfoEnd.cursorPos.x, charInfoEnd.cursorPos.y - settings.font.lineHeight);
    105.             // Debug.DrawLine(cornerStart, cornerEnd, Color.red, 10f);
    106.  
    107.             current.AddPoint(cornerStart);
    108.             current.AddPoint(cornerEnd);
    109.  
    110.             bounds.Add(current);
    111.         }
    112.         // END EDIT
    113.     }
    114.  
    115.  
    116.     // EDIT: Catch Input
    117.     public void OnPointerClick(PointerEventData eventData)
    118.     {
    119.         for (int i = 0; i < bounds.Count; i++)
    120.         {
    121.             // Debug.DrawLine(eventData.position, eventData.position + Vector2.up, Color.red, 10f);
    122.             if (bounds[i].Inside(transform.InverseTransformPoint(eventData.position)))
    123.             {
    124.                 Debug.Log(links[i]);
    125.             }
    126.         }
    127.     }
    128.  
    129.     class Bounds2D
    130.     {
    131.         public Vector2 min = Vector2.positiveInfinity;
    132.         public Vector2 max = Vector2.negativeInfinity;
    133.  
    134.         public void AddPoint(Vector2 point)
    135.         {
    136.             if (point.x < min.x)
    137.                 min.x = point.x;
    138.             if (point.y < min.y)
    139.                 min.y = point.y;
    140.             if (point.x > max.x)
    141.                 max.x = point.x;
    142.             if (point.y > max.y)
    143.                 max.y = point.y;
    144.         }
    145.  
    146.         public bool Inside(Vector2 point)
    147.         {
    148.             return (point.x > min.x && point.y > min.y && point.x < max.x && point.y < max.y);
    149.         }
    150.     }
    151. }
    It works just like the text component. To use it simply add the links on the top and put your string in [...] brakets.
    Textmesh pro is also very good but i don't like adding a lot of functions i don't need and don't understand.
    - look001
     
    Last edited: Jan 31, 2019
  49. rnnicoletti

    rnnicoletti

    Joined:
    Sep 27, 2017
    Posts:
    4
    Here's a component you can add alongside a TextMeshPro component that will allow you to run a function when text with a link tag gets clicked. The text that's inside the link is the address that gets opened, so put any additional tags (color, etc.) on the outside of the link tag. You could modify the code below to use the link ID instead of the link text if you wished, then you could write whatever text you wanted into the link and put the address in the ID instead. You do need distinct IDs, regardless; if you use the same ID for each link, it will only go in the TMP_Text.textInfo.linkInfo collection once (I don't know which of the link texts would be in the table in this case, either).

    The code below does use the event system, so you'll have to have everything set up properly for that, too (EventSystem in scene; raycaster on the camera, raycast target checked on the TextMeshPro component, etc.).

    The 12a scene in the TextMeshPro examples was very helpful for me, but that code essentially sets up a full-featured callback system for all the various library functions found in TMP_TextUtilities.cs. If you really just want to use the TextMeshPro link feature for opening up hyperlinks, you don't need to be able to add arbitrary delegates to each of these events.

    That's not to take away anything from that scene 12a code - I think it's pretty sweet stuff. But if someone finds themselves in this thread and confused by all of that, then here's a stripped-down version of the code from that example scene. The onEnter events were changed to an onClick event, all of the text utilities for watching anything but links were removed, and the delegation was just changed to a single HandleLinkClick function call that gets executed when a link is clicked. You can fill that function in with whatever you want.

    I've commented this in the code as well, but be aware of the injection attack ramifications of using Application.OpenURL. I've only tested this on the Canvas text object and not the world space one, but I believe it should work on either.

    Code (CSharp):
    1. using UnityEngine;
    2. using UnityEngine.EventSystems;
    3. using TMPro;
    4.  
    5. // Code adapted from Unity Package Manager TextMeshPro "Examples and Extras";
    6. // see Scene 12a and the TMP_TextEventHandler.cs script.
    7. public class TMP_LinkClickHandler : MonoBehaviour, IPointerClickHandler
    8. {      
    9.     // Used to look up link info
    10.     private TMP_Text m_TextComponent;
    11.  
    12.     // Used by the TMP_TextUtilities package to determine
    13.     // if the position of a click intersects with a link
    14.     private Camera m_Camera;
    15.     private Canvas m_Canvas;
    16.  
    17.     void Awake()
    18.     {
    19.         // Get a reference to the text component.
    20.         m_TextComponent = gameObject.GetComponent<TMP_Text>();
    21.  
    22.         // Get a reference to the camera rendering the text taking into consideration the text component type.
    23.         if (m_TextComponent.GetType() == typeof(TextMeshProUGUI))
    24.         {
    25.             m_Canvas = gameObject.GetComponentInParent<Canvas>();
    26.             if (m_Canvas != null)
    27.             {
    28.                 if (m_Canvas.renderMode == RenderMode.ScreenSpaceOverlay)
    29.                     m_Camera = null;
    30.                 else
    31.                     m_Camera = m_Canvas.worldCamera;
    32.             }
    33.         }
    34.         else {
    35.             m_Camera = Camera.main;
    36.         }
    37.     }
    38.  
    39.     public void OnPointerClick(PointerEventData eventData)
    40.     {
    41.         Debug.Log("TMP_LinkClickHandler.OnPointerClick(): Caught a click...");
    42.  
    43.         Vector3 clickPosition = new Vector3(eventData.position.x, eventData.position.y, 0);
    44.  
    45.         // Check if mouse intersects with any links.
    46.         int linkIndex = TMP_TextUtilities.FindIntersectingLink(m_TextComponent, clickPosition, m_Camera);
    47.  
    48.         // Handle new Link selection.
    49.         if (linkIndex != -1)
    50.         {              
    51.             // Get information about the link.
    52.             TMP_LinkInfo linkInfo = m_TextComponent.textInfo.linkInfo[linkIndex];
    53.  
    54.             // Send the event to any listeners.
    55.             HandleLinkClick(linkInfo.GetLinkID(), linkInfo.GetLinkText(), linkIndex);
    56.         }
    57.     }
    58.  
    59.     public void HandleLinkClick(string inLinkID, string inLinkText, int inLinkIndex)
    60.     {
    61.         Debug.Log("TMP_LinkClickHandler.HandleLinkClick(): Link ID #" + inLinkID + " clicked!");
    62.  
    63.         // Be aware of the injection attack ramifications of using this function:
    64.         // https://docs.unity3d.com/ScriptReference/Application.OpenURL.html
    65.         Application.OpenURL(inLinkText);
    66.     }
    67. }
     
    LilGames and SkutteOleg like this.
  50. zoranigic

    zoranigic

    Joined:
    Oct 4, 2019
    Posts:
    16
    Just reminder to myself,
    Unity UI Text component have "Ritch Text" check box that is only displaying HTML tags (link is not clickable - use button)