如何在一个UI文本字段中重复显示不同的字符串?

huangapple go评论117阅读模式
英文:

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

huangapple
  • 本文由 发表于 2023年5月25日 17:16:21
  • 转载请务必保留本文链接:https://go.coder-hub.com/76330669.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定