-
Notifications
You must be signed in to change notification settings - Fork 0
Coroutine Runner
Created by: @toverux
Authors: @toverux
SDKs needed: .NET (NuGet)
A simple helper class to run Unity coroutines from anywhere and convert them to C# Tasks.
As you may know, Unity only allows to start coroutines from MonoBehaviour
classes.
This is a bit annoying with DOTS are we are typically not using MonoBehaviour
s, but we do often need to work with coroutines.
This means you have to create an empty GameObject
and attach an empty MonoBehaviour
just to call StartCoroutine()
.
Clunky, that's why UDK does that for you.
using UrbanDevKit.Utils;
CoroutineRunner.Start(MyCoroutine());
// you can also stop them:
var coroutine = CoroutineRunner.Start(MyCoroutine());
CoroutineRunner.Stop(coroutine);
The extension method CoroutineRunner.RunAsTask(IEnumerator, CancellationToken?)
allows you to easily wrap a coroutine in a Task, which is generally easier to use especially in already TAP-based code.
Wrapping a coroutine yourself can be clunky and error prone (error handling, return, cancellation...), that's why UDK also exposes a shortcut for that.
using UrbanDevKit.Utils;
await MyCoroutine().RunAsTask();
// Using a cancellation token, which will call StopCoroutine():
var cts = new CancellationTokenSource();
await MyCoroutine().RunAsTask(cts.Token);
cts.Cancel();
Note that the Task that is returned:
- Is immediately scheduled for execution (it is not a "cold" Task awaiting to be awaited to start).
- Rethrows coroutine exceptions.
- Stops the coroutine if passed a CancellationToken and marks the Task as Canceled (which throws a TaskCanceledException).
- If the enumerator ends, The Task resolves with the last value the coroutine yielded.
- Shared State Share state between assemblies without linking
- Coroutine Runner Helper to start coroutines from anywhere or wrap them into Tasks.
-
cs2/*
Types as a Dependency Get rid of thattypes/
folder from your codebase.
- Cooperative Preloading Prevent the user to load a game while mods are preloading