【问题标题】:Startcoroutine is not working启动协程不工作
【发布时间】:2016-09-10 14:45:55
【问题描述】:

我正在尝试在显示两个文本之间进行延迟。但它不起作用。 代码是:

public class Class1: MonoBehaviour 
{
    public Text text1, text2;
    public bool inArea = false;

    private void Update () 
    {
       if (!inArea)
       {
           inArea     = true;
           text1.text = "";
           text2.text = "text2";
           StartCoroutine(timer());
           text2.text = "text3";            
      }
 }
 IEnumerator timer()
 {
     yield return new WaitForSeconds(100);
 }

我也试过WaitForSecondsRealTime()。它也不起作用。

【问题讨论】:

    标签: unity3d coroutine


    【解决方案1】:

    我想你有点误解了。

    如果协程本身没有延迟 yield,则协程将与其他东西(在您的情况下为 text2.text = "text3")并行运行(为此,您需要从协程调用协程或使用 javascript 来完成这是内部的)。

    您要么必须将所有代码移至应受延迟影响的协程,如下所示:

    private void Update () 
    {
        if (!inArea)
        {
            inArea = true;
            StartCoroutine(timer());          
        }
    }
    
    IEnumerator timer()
    {
        text1.text = "";
        text2.text = "text2";
    
        yield return new WaitForSeconds(100);
        text2.text = "text3";  
    }
    

    或者您也可以通过将void Update 更改为IEnumerator Update 来使Update 成为协程。

    在你目前的情况下,第一个应该没问题。

    【讨论】:

    • 许多新的 Unity 程序员不了解协程背后发生了什么以及它是如何工作的,这会导致像这样的问题......
    • 感谢您的帮助。我实际上不知道协程的工作。我搜索了延迟并找到了一些此类解决方案。谢谢
    猜你喜欢
    • 2020-04-12
    • 2017-10-01
    • 2017-12-11
    • 1970-01-01
    • 1970-01-01
    • 2019-02-25
    • 1970-01-01
    • 1970-01-01
    • 2014-04-19
    相关资源
    最近更新 更多