Skip to main content

UMT

Important Attention Reminder

Coding Style wiki


UMT (Unity Main Thread) is a Unity main-thread dispatcher (a lazy MonoBehaviour singleton). Jobs (Action) queued from any thread are executed in order in Update on the Unity main thread (the enqueue operation is protected by a thread lock), and it also supports starting and stopping coroutines.

NamespaceOxGKit.Utilities.UnityMainThread
Typepublic class UMT : MonoBehaviour
SourceUMT.cs
using OxGKit.Utilities.UnityMainThread;

Attention The first access to UMT.worker automatically creates a persistent object named [UMT] (parented under an OxGKit container with DontDestroyOnLoad); avoid first-touching it during application teardown, or a stray object may be created.

Quick Start

using OxGKit.Utilities.UnityMainThread;
using System.Threading.Tasks;
using UnityEngine;

public class UMTDemo : MonoBehaviour
{
private void Start()
{
Task.Run(() =>
{
// After finishing work on a background thread...
var result = 1 + 1;

// Queue work that touches Unity APIs back onto the main thread
UMT.worker.AddJob(() =>
{
Debug.Log($"Result: {result} (main thread)");
this.transform.position = Vector3.zero;
});
});
}
}

General Rules

Execution Timing

  • Jobs queued via AddJob are all executed in order within UMT's Update (FIFO).
  • AddJob is protected by a thread lock and is safe to call from any thread; the coroutine methods must still be used on the main thread.

Members

MemberDescription
public static UMT workerGets the UMT singleton (the persistent object is created on first access).

Method Overview

MethodDescription
AddJobQueues a job to run in Update on the main thread.
RunCoroutineStarts a coroutine (IEnumerator or method name).
CancelCoroutineStops a coroutine (IEnumerator or method name).
CancelAllCoroutinesStops all coroutines started by UMT.
ClearClears the pending job queue.

AddJob

public void AddJob(Action newJob)

Queues a job to be executed in order in Update on the main thread; callable from any thread (thread lock protected).

UMT.worker.AddJob(() =>
{
// Do main thread job
});

RunCoroutine

public void RunCoroutine(IEnumerator routine)

public void RunCoroutine(string methodName)

Starts a coroutine with UMT as the host; useful for running coroutines from non-MonoBehaviour classes.

UMT.worker.RunCoroutine(this.MyRoutine());

Reminder Following Unity's StartCoroutine(string) semantics, the string overload can only start methods defined on UMT itself; prefer the IEnumerator overload in general.

CancelCoroutine

public void CancelCoroutine(IEnumerator routine)

public void CancelCoroutine(string methodName)

Stops the given coroutine (pass the same IEnumerator instance or method name used to start it).

CancelAllCoroutines

public void CancelAllCoroutines()

Stops all coroutines started by UMT.

Clear

public void Clear()

Clears the pending job queue (jobs that already ran are unaffected).