There is currently no equivalent method for for yield return null
.
I was going to say it's not possible since async can be called in another Thread
other than the main Thread
which can throw exceptions since you can't use Unity's API in another Thread but it looks like Unity fixed the Thread issue by implementing their own async context in Unity 5.6.0b5 and above.
It' still possible to do but you have to implement it yourself or use an existing API. The UnityAsync
API can do this already. You can get it here. The NextUpdate
function replaces the yield return null
instruction.
Examples:
Your usual coroutine code:
private IEnumerator RunEachFrame()
{
while (true)
{
print("Run Each frame right before rendering");
yield return null;
}
}
The equivalent async code:
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();
}
}
}
Notice how the script inherits from AsyncBehaviour
instead of MonoBehaviour
.
If you really want to inherit from MonoBehaviour
instead of AsyncBehaviour
and still use this API, call the NextUpdate
function directly as Await.NextUpdate()
.Here is a complete equivalent example:
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
}
}
}
Below are the complete supported wait functions:
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)
All these can be found in the Await
class just in-case they get renamed or removed.
If you ever run into issues with this API, see Unity's forum post dedicated to it and ask questions there.
Unity does provide one important piece for us however. As you can see in the above example, our async methods will be run on the main unity thread by default. In non-unity C# applications, async methods are often automatically run on separate threads
stevevermeulen.com/index.php/2017/09/… – Eligibility