【问题标题】:C# Unity trying to figure out how to use CoroutineC# Unity 试图弄清楚如何使用 Coroutine
【发布时间】:2013-04-11 16:41:52
【问题描述】:

我有以下代码...

StartCoroutine(GetSuggestions());

IEnumerator GetSuggestions() {
    longExecutionFunction(); // this takes a long time
    yield return null;
}

如何使用协程来保持主程序流程继续进行?目前当它达到 longExecutionFunction();程序停止几秒钟。如果整个程序在此过程中继续工作,我会很高兴。我该怎么做?

【问题讨论】:

    标签: c# unity3d coroutine


    【解决方案1】:

    不使用线程,假设你可以修改longExecutionFunction,它看起来像这样:

    void longExecutionFunction()
    {
        mediumExecutionFunction();
        mediumExecutionFunction();
        while(working)
        {
            mediumExecutionFunction();
        }
    }
    

    您可以将其修改为:

    IEnumerator longExecutionFunction()
    {
        mediumExecutionFunction();
        yield return null;
        mediumExecutionFunction();
        yield return null;
        while(working)
        {
            mediumExecutionFunction();
            yield return null;
        }
    }
    

    然后修改调用代码如下:

    StartCoroutine(GetSuggestions());
    
    IEnumerator GetSuggestions() {
        yield return longExecutionFunction();
        //all done!
    }
    

    这样每次更新都会做一件“中等长度的事情”,防止游戏挂起。是否以及如何分解longExecutionFunction 中的工作取决于您在其中的代码。

    【讨论】:

      【解决方案2】:

      您需要在另一个线程中启动 longExecutionFunction。你可能想看看这篇文章来了解线程:http://msdn.microsoft.com/en-us/library/system.threading.thread.aspx

      代码示例:

      var thread = new System.Threading.Thread(new System.Threading.ThreadStart(() => {
          longExecutionFunction();
      }));
      thread.Start();
      

      如果您不熟悉线程,您应该在使用它们之前阅读它们。 :)

      【讨论】:

      • Unity 游戏引擎不是线程安全的,强烈建议不要使用线程
      • 协程不可以吗?
      【解决方案3】:

      您应该将Threads 与协程结合使用。

      StartCoroutine(MyCoroutine());
      
      [...]
      
      IEnumerator MyCoroutine()
      {
          Thread thread = new Thread(() =>
          {
              longExecutionFunction();
          });
      
          thread.Start();
      
          while (thread.IsAlive) yield return 0;
      
          // ... Use data here
      }
      

      但是,您不能在 longExecutionFunction 中使用任何统一对象或方法,因为统一不是线程安全的。所以你需要计算longExecutionFunction中的所有数据,并在方法返回时初始化unity对象。

      【讨论】:

      • AFAIK 你不能在网络播放器中创建线程,所以即使longExecutionFunction() 没有接触统一对象,它仍然会限制平台。
      • @MikeMcFarland forum.unity3d.com/threads/76087-WebPlayer-Multi-threading 这个链接告诉你别的东西。
      • 太棒了,感谢指正。很高兴知道它的可能。
      猜你喜欢
      • 2020-08-27
      • 2023-03-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-03-11
      • 2021-03-24
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多