Changing Characters in TMPro

Changing Characters in TMPro

To change a character in a specific place in a text object using the TextMesh Pro (TMPro) Unity plugin, you can use the SetCharArray method of the TMP_Text class. This method takes an array of characters as input and allows you to replace the existing characters in the text object with the new characters.

Bellow an example of how you can use the SetCharArray method to change a character in the middle of a string:

using UnityEngine;
using TMPro;

public class ChangeCharacterExample : MonoBehaviour
{
    public TMP_Text textObject;

    void Start()
    {
        // Get the current text as a character array
        char[] currentText = textObject.text.ToCharArray();

        // Change the character at index 5
        currentText[5] = 'X';

        // Set the new character array as the text for the text object
        textObject.SetCharArray(currentText);
    }
}

using UnityEngine;
using TMPro;

public class ChangeCharacterExample : MonoBehaviour
{
    public TMP_Text textObject;

    void Start()
    {
        // Get the current text as a character array
        char[] currentText = textObject.text.ToCharArray();

        // Change the character at index 5
        currentText[5] = 'X';

        // Set the new character array as the text for the text object
        textObject.SetCharArray(currentText);
    }
}

This script would replace the character at the 6th position in the text object with an 'X'. Note that the index of the first character is 0, so the 6th character has an index of 5.

You can also use the SetCharArray method to replace multiple characters at once by setting the char[] array to have the desired characters. For example, to replace the 6th and 7th characters with 'XY', you could do the following:


char[] currentText = textObject.text.ToCharArray();

currentText[5] = 'X';

currentText[6] = 'Y';

textObject.SetCharArray(currentText);