Unity游戏开发:如何在单个UI Text快速循环显示不同字符串?
实现UI Text快速循环字符串后随机固定显示
你原来的代码之所以没效果,是因为foreach循环在一帧内就完成了所有字符串的设置,人眼根本捕捉不到切换过程,看起来就像直接显示了最后一个字符串。要实现逐个快速切换的效果,得用Unity的**协程(Coroutine)**来控制帧间延迟。
直接用下面的代码替换你的逻辑:
using UnityEngine; using UnityEngine.UI; using System.Collections; public class TextCycler : MonoBehaviour { public Text buttonText; // 把你的UI Text拖到这个字段上 private string[] arr = new string[3]; void Start() { arr[0] = "option1"; arr[1] = "option2"; arr[2] = "option3"; StartCoroutine(CycleAndRandomizeText()); } IEnumerator CycleAndRandomizeText() { // 先循环3轮字符串,让切换效果更明显 int totalCycles = 3; for (int cycle = 0; cycle < totalCycles; cycle++) { // 逐个显示数组里的每个字符串 foreach (string s in arr) { buttonText.text = s; // 每个字符串显示0.1秒,数值越小切换越快 yield return new WaitForSeconds(0.1f); } } // 循环结束后随机选一个固定显示 int randomIdx = Random.Range(0, arr.Length); buttonText.text = arr[randomIdx]; } }
关键说明:
- 协程通过
yield return new WaitForSeconds(0.1f)让程序暂停指定时间,这样每个字符串都能被肉眼看到 - 调整
totalCycles可以控制循环的轮数,轮数越多,"随机选择"的感知越强 - 最后用
Random.Range随机挑选数组中的一个元素,固定显示
注意事项:
- 如果你的项目用的是TextMeshPro,把代码里的
Text改成TMP_Text,同时把buttonText.text替换成buttonText.SetText(s) - 一定要在Inspector面板把你的UI Text组件拖到脚本的
buttonText变量上
内容的提问来源于stack exchange,提问作者Okashi
相关产品推荐
相关产品推荐

