Skip to content

Coroutine Runner

Morgan Touverey Quilling edited this page Jul 14, 2024 · 5 revisions

Created by: @toverux
Authors: @toverux
SDKs needed: .NET (NuGet)

Overview

A simple helper class to run Unity coroutines from anywhere and convert them to C# Tasks.

Usage

Run Coroutine From Anywhere

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 MonoBehaviours, 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);

Convert a Coroutine to a Task

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.

Features & Helpers

.NET-only Features

  • Shared State Share state between assemblies without linking
  • Coroutine Runner Helper to start coroutines from anywhere or wrap them into Tasks.

UI-only Features

.NET+UI Features

Contributing

Clone this wiki locally