unity-game-enginetextmeshpro

TextMeshPro RunTime Insert additional Text via Script


Platform:


OS: Win10
Unity V.: 2022.2.19f1
textmeshpro V.: 2023.1
Language: C#
Build target: PC

Preamble:

Note; I have already looked over the suggested posts before making this one.

I can't find a solution for this anywhere. All I can find is how to replace the whole text body or add style / other things as the Author in the editor >Not< as the end user in a build at runtime.

I want to make a WYSIWYG text editor much like the Post editor on these forums.

I need to be able to insert rich text into the text body at a specific index during runtime e.g. "<b>" or "<b/>". And call textmeshpro to parse the inserted rich text tags.

I've looked at the documentation for C# and TMP but am unable to resovle using Insert() or any other means to insert into a string. I've exhaust my options searches only coming up with the same posts I've already read.

I Need a new set of terms, a new line of inquery, or a example of how to implent a working means of inserting.

If someone could post a stripped down working model that would be super!

Question:

How do I insert a string or rich text tag at a given index on a build during runtime via script.

NOT replace the whole text body if possible.

Clarification:

I'm aware you can access the TMP_InputField.Text component. I am unable to insert at an Index.

Here is some stripped down code of my problem.
I have a canvas TMP_InputField. There is a monobehaviour script that has a serialized field for the TMP object and a public method to insert "BB" into the inputfield.text property at index 0 for debbugging. To invoke that function I've got a button on the same canvas.

[SerializeField]
private TMP_InputField someTMPObject;

public void ButtonFunc_Insert()
{
//Insert Text at Index - Doesn't Work:
someTMPObject.text.Insert(0, "start of text array ");

//Replacing Text - works:
someTMPObject.text = "Replace all text.";

//Appending Text - works:
someTMPObject.text += "Add more text to the end!";
}

Solution

  • Use (string).Insert to insert text at a specific index.
    (string).Insert returns a new instance of string with the inserted text.

    var text = someTMPObject.text; // Get a copy of the existing text string
    
    text = text.Insert(0, "start of text array "); // Modify string using Insert
    
    someTMPObject.text = text; // Assign string back to TMP object