Yield and Async - ManeFunction/ManeTools-Unity GitHub Wiki
Yield instructions
Poll a predicate every waitSeconds. Optional checkPredicateFirst. Scaled vs unscaled time:
| Type | Waits until / while | Time |
|---|---|---|
WaitForSecondsUntil |
until true | scaled |
WaitForSecondsWhile |
while true | scaled |
WaitForSecondsRealtimeUntil |
until true | unscaled |
WaitForSecondsRealtimeWhile |
while true | unscaled |
yield return new WaitForSecondsUntil(() => player.IsReady, .25f);
yield return new WaitForSecondsRealtimeWhile(() => Time.timeScale == 0, .1f);
MainThreadDispatcher
Unity objects and most engine calls run on the main thread. A Task, worker thread, or socket callback that finishes elsewhere cannot set UI text, instantiate, or call into a behaviour. RunOnMainThread queues that work, and the dispatcher runs it on the next Update.
Use it when background work has to come back onto a scene object.
MainThreadDispatcher.RunOnMainThread(() => uiText.text = result);
Must exist before you call RunOnMainThread (place it in a scene, or touch Instance on the main thread first). If it is not ready, the call logs an error and returns. Actions run on the next Update.
Extensions
ToCoroutine
Yields once per frame until task.IsCompleted, then calls (true, task.Result), or (false, default) if the task faulted or was canceled. A null callback is ignored.
StartCoroutine(task.ToCoroutine((ok, value) => { /* ... */ }));
Delayed
Runs the action after delay seconds of scaled time (WaitForSeconds). A null action returns null. delay <= 0 invokes the action immediately and returns null.
this.Delayed(() => Fire(), .25f);
DelayedFrames
Same as Delayed, counted in frames (yield return null once per frame). A null action returns null. frames <= 0 invokes immediately and returns null.
this.DelayedFrames(() => Fire(), 2);
TryKillCoroutine
Stops the coroutine and sets the reference to null. Returns false when the coroutine is already null or the behaviour is destroyed.
this.TryKillCoroutine(ref _loop);