Unity Coroutine yield返回null EQUIVALENT with Task async await

问题描述 投票:2回答:1

在异步方法中,Coroutine中的yield return null;(在Update中运行每个帧)的等价物是什么?

我找到的最近的是await Task.Delay(1);,但它不会每帧运行。

private IEnumerator RunEachFrame()
{
    while (true)
    {
        print("Run Each frame right before rendering");
        yield return null;
    }
}

async void DoNotRunEachFrame()
{
    while (true)
    {
        await Task.Delay(1); // What is the equivalent of yield return null here ?
    }
}
c# unity3d async-await coroutine .net-4.6
1个回答
3
投票

目前没有用于yield return null的等效方法。

我打算说这是不可能的,因为async可以在另一个Thread中调用,而不是主Thread可以抛出异常,因为你不能在另一个Thread中使用Unity的API,但它像Unity一样通过实现自己的异步修复了Thread问题Unity 5.6.0b5及更高版本中的上下文。


它仍然可以,但你必须自己实现它或使用现有的API。 looks API已经可以做到这一点。你可以得到它UnityAsynchere函数取代了NextUpdate指令。

例子:

你通常的协程代码:

yield return null

等效的异步代码:

private IEnumerator RunEachFrame()
{
    while (true)
    {
        print("Run Each frame right before rendering");
        yield return null;
    }
}

注意脚本如何从using UnityAsync; using System.Threading.Tasks; public class UpdateLoop : AsyncBehaviour { void Start() { RunEachFrame(); } // IEnumerator replaced with async void async void RunEachFrame() { while(true) { print("Run Each frame right before rendering"); //yield return null replaced with await NextUpdate() await NextUpdate(); } } } 而不是AsyncBehaviour继承。


如果你真的想继承MonoBehaviour而不是MonoBehaviour并仍然使用这个API,请直接调用AsyncBehaviour函数作为NextUpdate.Here是一个完整的等效示例:

Await.NextUpdate()

以下是完整支持的等待功能:

  • using UnityAsync; using System.Threading.Tasks; public class UpdateLoop : MonoBehaviour { async void Start() { await RunEachFrame(); } async Task RunEachFrame() { while(true) { print("Run Each frame right before rendering"); await Await.NextUpdate(); // equivalent of AsyncBehaviour's NextUpdate } } }
  • NextUpdate
  • NextLateUpdate
  • NextFixedUpdate
  • Updates(int framesToWait)
  • LateUpdates(int framesToWait)
  • FixedUpdates(int stepsToWait)
  • Seconds(float secondsToWait)
  • SecondsUnscaled(float secondsToWait)
  • Until(Func<bool> condition)
  • While(Func<bool> condition)
  • Custom(CustomYieldInstruction instruction)

所有这些都可以在AsyncOp(AsyncOperation op)类中找到,只要它们被重命名或删除。

如果您遇到过这个API的问题,请参阅专用于它的Unity论坛Await并在那里提问。

© www.soinside.com 2019 - 2024. All rights reserved.