[HOWTO] How To: Add Custom Tags to TextMesh Pro

Announcements, support questions, and discussion for the Dialogue System.
Post Reply
User avatar
Tony Li
Posts: 20649
Joined: Thu Jul 18, 2013 1:27 pm

[HOWTO] How To: Add Custom Tags to TextMesh Pro

Post by Tony Li »

To add and process custom tags in TextMesh Pro (TMP), use TMP's <link> tag with custom text.

Hook into the typewriter effect's onCharacter() UnityEvent, and check the TMP component's link info at the current character position. To optimize, hook into the typewriter effect's onBegin() UnityEvent and cache the link positions when the typewriter begins.

An example script is below.

For example, say the text to type is:

"This is some text. <link="special"> And more text."

After "This is some text.", the code in OnTypeCharacter will see that the typewriter is at the link named "special".

TMPTypewriterHandleCustomLinkTags .cs

Code: Select all

using UnityEngine;
using TMPro;
using PixelCrushers.DialogueSystem;

public class TMPTypewriterHandleCustomLinkTags : MonoBehaviour
{
    TextMeshProUGUI textMeshPro;
    TextMeshProTypewriterEffect typewriter;

    private void Start()
    {
        textMeshPro = GetComponent<TextMeshProUGUI>();
        typewriter = textMeshPro.GetComponent<TextMeshProTypewriterEffect>();
        typewriter.onBegin.AddListener(OnBeginTyping);
        typewriter.onCharacter.AddListener(OnTypeCharacter);
    }

    private void OnBeginTyping()
    {
        var text = TextMeshProTypewriterEffect.StripRPGMakerCodes(Tools.StripTextMeshProTags(textMeshPro.text));
        foreach (TMP_LinkInfo linkInk in textMeshPro.textInfo.linkInfo)
        {
            // Cache linkInfo.linkTextfirstCharacterIndex so you don't have to 
            // loop through linkInfo every time onCharacter is invoked.
        }
    }

    private void OnTypeCharacter()
    {
        foreach (TMP_LinkInfo linkInfo in textMeshPro.textInfo.linkInfo)
        {
            if (linkInfo.linkTextfirstCharacterIndex == textMeshPro.maxVisibleCharacters)
            {
                Debug.Log("Do something at character position " + linkInfo.linkTextfirstCharacterIndex);
                // You can read linkInfo.GetLinkText() or linkInfo.GetLinkID().
            }
        }
    }
}
Post Reply