如何在添加到TMPro UI元素时设置单词的颜色?



我有一个脚本,当你拿起单词时,它会按照顺序添加单词,但是当你的顺序出错时,它会填充应该按照该顺序出现的单词。下面列出了大部分脚本,但我正在努力寻找一个解决方案,使正确的单词(在OnMouseDown else if语句中)添加白色,其他两个SetText调用添加红色的单词。

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using TMPro;
public class WordOrderOnDestroy : MonoBehaviour
{
private TextMeshProUGUI pickedUpWords;
void Start()
{
pickedUpWords = GameObject.Find("Picked Up Words").GetComponent<TextMeshProUGUI>();
}
void OnMouseDown() 
{
if (gameObject.name != memorySlotOne[currentIndexOne])
{
GetComponent<MeshRenderer>().material = redForWrong;
StartCoroutine(DestroyObjects());
}
else if (gameObject.name == memorySlotOne[currentIndexOne])
{
Debug.Log("Correct!");
pickedUpWords.SetText(pickedUpWords.text + memorySlotOne[currentIndexOne] + " ");
Destroy(gameObject);
}
}
IEnumerator DestroyObjects()
{
for (int i = currentIndexOne; i < memorySlotOne.Count; i++)
{
if (memorySlotOne[i] == gameObject.name)
{
Debug.Log("And then, " + (memorySlotOne[i]));
Destroy(gameObject);
memoryListManager.currentIndexOne++;
pickedUpWords.SetText(pickedUpWords.text + memorySlotOne[i] + " ");
break;
}
// Append the current word to the text mesh pro UI element
pickedUpWords.SetText(pickedUpWords.text + memorySlotOne[i] + " ");
yield return new WaitForSeconds(rateOfDestroy);
Destroy(GameObject.Find(memorySlotOne[i]));
Debug.Log("Next correct word was: " + (memorySlotOne[i]));
}

}
}

TextMeshPro支持富文本,因此您可以简单地将您的单词包装在例如

"<color=red>" + memorySlotOne[currentIndexOne] + "</color>"

可能需要启用TEMP_Text.richText(虽然应该是默认的)

最新更新