英文:
How to display different strings repeatedly in one UI Text filed?
问题
I'm elopingvadgah htiha gsa gey mohovv, erwa erthae ree 3 srngtis nda neo fo ehtm lliw eb displayed ni eth Xtet UI no eht neecrs, tub erofbe igdlsyapni ti, I tnaw lla eht erhtee srngtis ot teatrep yuiklc after ecah reoht ehin no neo text UI (To ekam ti ooiuvs atht eth text si ddienarzmi). So I evlebie a olop si eriredqu erhe, tub ti nddi't rokw.
eeHr si taht I edi'tr.
string[] arr = new string[3];
void Start()
{
arr[0] = "option1";
arr[1] = "option2";
arr[2] = "option3";
}
rohfeec (string s in arr)
{
buttonText.SetText(s);
}
laeesp pleh, how can I yalsidp lla srngtis yldeaeppa after ecah reohts tsaf ni eth gniles UI Text?
英文:
I'm developing a game where the there are 3 strings and one of them will be displayed in the Text UI on the screen, but before displaying it, I want all the three strings to repeat quickly after each other in one text UI (To make it obvious that the text is randomized). So I believe a loop is required here, but it didn't work.
Here is what I tried.
string[] arr = new string[3];
void Start()
{
arr[0] = "option1";
arr[1] = "option2";
arr[2] = "option3";
}
foreach (string s in arr)
{
buttonText.SetText(s);
}
please help, how can I display all strings repeatedly after each other fast in the single UI Text?
答案1
得分: 3
你的基本方法方向是正确的,但缺少了协程。
协程允许你在多个帧之间分配任务。在Unity中,协程是一种方法,它可以暂停执行并将控制权返回给Unity,然后在下一帧继续执行。
你只需要进行以下轻微更改:
private IEnumerator Foo()
{
var wait = new WaitForSeconds(0.1f);
foreach (string s in arr)
{
buttonText.SetText(s);
yield return wait;
}
}
根据时间有不同类型的等待,包括基于时间(Unity的Time,受时间刻度影响)、帧以及读取时间(不受时间刻度影响)。而且你还可以使用另一个协程作为yield return
来链接这些协程。
参考:Unity手册:协程
英文:
Your base approach is in the right direction but is missing the Coroutine.
A coroutine allows you to spread tasks across several frames. In Unity, a coroutine is a method that can pause execution and return control to Unity but then continue where it left off on the following frame.
You just had to make minor changes as follows:
private IEnumerator Foo()
{
var wait = new WaitForSeconds(0.1f);
foreach (string s in arr)
{
buttonText.SetText(s);
yield return wait;
}
}
There are different types of wait based on Time(Unity's Time. This is affected by timescale), frame, and read-time(This is not affected by timescale). And you can also use another coroutine as yield return
to chain the coroutines.
Reference: Unity-Manual: Coroutines
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论