简体   繁体   中英

How to replace char color in text?

I'm working with a typing game, and i want to change the color of letter in the text to red, only when i typed it correctly… like this: thanks in advance :-)

 string myString = txt.text;
    char[] myChars = myString.ToCharArray();


    foreach (char c in myChars)
    {
        txt.text = txt.text.Replace(c.ToString(), "<color=red>"+c+"</color>");
        break;
    }

在此处输入图片说明

Updated Output

A whole UI Text color is changed with Text.color :

public Text txt;

void Start()
{
    txt.color = Color.red;
}

It looks like you want to change individual character color. Unity supports Rich Text which let's you change the font style, size and color of each character in a text. This means that enclosing the character with <color=yourcolor> and </color> will change the color.

public Text txt;

void Start()
{
    string goodText = "<color=red>G</color>ood";
    txt.text = goodText;
}

The character G will be red in the example above. All other character will be in their default color which is black. You can do this for all other characters as well.

In the example below, Goo will be red and the d will be black(default color).

string goodText = "<color=red>Goo</color>d";

This should work, give it a try.

public UnityEngine.UI.Text myText;
 // Get index of character.
 int charIndex = myText.text.IndexOf ("S");
 // Replace text with color value for character.
 myText.text = myText.text.Replace (myText.text [charIndex].ToString (), "<color=#000000>" + myText.text [charIndex].ToString () + "</color>");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM