如何为添加到TMPro UI元素的文字设置对应颜色:正确白/错误红?
解决方案
要实现不同场景下文本的颜色区分,直接利用TextMeshPro的富文本标签即可,通过<color>标签为对应文本指定颜色。以下是修改后的完整代码,已针对三处SetText调用添加了颜色控制:
using System.Collections; using System.Collections.Generic; using UnityEngine; using TMPro; public class WordOrderOnDestroy : MonoBehaviour { private TextMeshProUGUI pickedUpWords; // 补充你原脚本中已定义的变量(比如memorySlotOne、currentIndexOne等) public List<string> memorySlotOne; public int currentIndexOne; public Material redForWrong; public float rateOfDestroy; public MemoryListManager memoryListManager; 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 + $"<color=white>{memorySlotOne[currentIndexOne]}</color> "); 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 + $"<color=red>{memorySlotOne[i]}</color> "); break; } // 填充的正确顺序单词显示红色 pickedUpWords.SetText(pickedUpWords.text + $"<color=red>{memorySlotOne[i]}</color> "); yield return new WaitForSeconds(rateOfDestroy); Destroy(GameObject.Find(memorySlotOne[i])); Debug.Log("Next correct word was: " + (memorySlotOne[i])); } } }
关键修改说明
- 正确选中单词时,用
<color=white>包裹文本,强制显示为白色 - 错误场景下的两处文本添加(包括填充顺序单词、错误匹配的单词),用
<color=red>包裹,强制显示为红色 - 如果需要更精确的颜色值,可以替换为十六进制格式,比如
<color=#FFFFFF>(白色)、<color=#FF0000>(红色)
内容的提问来源于stack exchange,提问作者BearHandz
相关产品推荐
相关产品推荐

