Search Unity

Replacing characters at runtime while preserving richtext tags

Discussion in 'UGUI & TextMesh Pro' started by CoraBlue, Feb 7, 2020.

  1. CoraBlue

    CoraBlue

    Joined:
    Nov 16, 2017
    Posts:
    60
    I'm using links to tag portions of my text and 'scramble' them per frame, to create to appearance in-game as though the text has been redacted, or corrupted. Here is the relevant section of code.


    for (int i = 0; i < dialogText.textInfo.linkCount; i++)
    {
    if (dialogText.textInfo.linkInfo[i].GetLinkID() == "Scramble")
    {
    var startingCharacter = dialogText.textInfo.linkInfo[i].linkTextfirstCharacterIndex;
    var endCharacter = dialogText.textInfo.linkInfo[i].linkTextfirstCharacterIndex + dialogText.textInfo.linkInfo[i].linkTextLength;
    for (int onCharacter = startingCharacter; onCharacter < endCharacter; onCharacter++)
    {
    string garbledTable = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
    var r = Random.Range(0, garbledTable.Length);

    dialogText.textInfo.characterInfo[onCharacter].character = garbledTable[r];
    }
    }
    }


    The issue I'm running into is that changing the characterInfo of a TMP object does not update the text contents. I'm unsure how to resolve this problem as linkTextFirstCharacterIndex ignores tags, making the use of SetText difficult. I want to change single characters post formatting at runtime. Is there a method for this?
     
  2. CoraBlue

    CoraBlue

    Joined:
    Nov 16, 2017
    Posts:
    60
    I've discovered a solution which seems hacky and could be prone to breaking, but in case anyone needs a working version this was my solution.


    var info = dialogText.textInfo.linkInfo[i];
    int startingCharacter = dialogText.text.IndexOf('>', info.linkIdFirstCharacterIndex + info.linkIdLength) + 1;
    int endCharacter = dialogText.text.IndexOf("</link>", info.linkIdFirstCharacterIndex + info.linkIdLength + 1);

    ...

    dialogText.text = dialogText.text.Remove(onCharacter, 1);
    dialogText.text = dialogText.text.Insert(onCharacter, garbledTable[r].ToString());



    Can I formally request a feature? It seems like we could greatly benefit from a linkTextfirstCharacterIndexRaw or linkTextfirstCharacterIndexUnParsed. It seems so much more intuitive and could be very easily implemented to the struct.
     
  3. CoraBlue

    CoraBlue

    Joined:
    Nov 16, 2017
    Posts:
    60
    Here's the code in action, works (for now) even with other tags present.