UnityThread is a singleton-based threading utility for Unity that allows developers to enqueue tasks safely and execute them within the Unity engine's update loop. It ensures thread safety when executing tasks that interact with Unity’s main thread.
Ensure that your Unity project has access to the necessary UnityEngine namespace before using UnityThread.
using Maphatar.UnityThread;- Singleton-based execution: Ensures a single instance of
UnityThreadexists in the scene. - Task queuing: Supports enqueuing tasks as
ActionorIEnumerator. - Automatic execution: Executes pending jobs in Unity’s
FixedUpdate()loop. - Exception handling: Captures errors and prevents the queue from breaking unexpectedly.
- Safe coroutine stopping: Stops coroutines safely to prevent errors.
To access UnityThread, use:
UnityThread thread = UnityThread.Instance;UnityThread.Instance.EnqueueTask(() => Debug.Log("This runs on Unity’s main thread"));UnityThread.Instance.EnqueueTask(MyCoroutine());Example coroutine:
IEnumerator MyCoroutine()
{
Debug.Log("Start coroutine");
yield return new WaitForSeconds(2);
Debug.Log("Coroutine finished");
}To check if there are any pending tasks:
bool hasJobs = UnityThread.Instance.HasPendingJob();To add a message to the internal log queue:
UnityThread.Instance.Log("This is a log message");To safely stop a coroutine:
Coroutine myCoroutine = StartCoroutine(MyCoroutine());
UnityThread.Instance.SafelyStopCoroutine(myCoroutine);The UnityThread instance persists across scenes using:
DontDestroyOnLoad(gameObject);This ensures that tasks remain available throughout the application’s lifecycle.
Below is an example of how to use UnityThread to execute tasks on Unity’s main thread.
void Start()
{
UnityThread.Instance.EnqueueTask(() => Debug.Log("Task executed in UnityThread"));
UnityThread.Instance.EnqueueTask(MyCoroutine());
}
IEnumerator MyCoroutine()
{
Debug.Log("Coroutine started");
yield return new WaitForSeconds(3);
Debug.Log("Coroutine completed");
}UnityThread is particularly useful when working with background threads that need to update Unity’s main thread safely.
void Start()
{
Thread backgroundThread = new Thread(BackgroundTask);
backgroundThread.Start();
}
void BackgroundTask()
{
Thread.Sleep(2000); // Simulating heavy computation
UnityThread.Instance.EnqueueTask(() => Debug.Log("Background thread completed. Now updating Unity UI."));
}If you're fetching data from a server in a background thread, you can safely update the UI in Unity’s main thread:
void FetchDataFromServer()
{
Thread backgroundThread = new Thread(() =>
{
string data = "Sample API Data"; // Simulated API response
Thread.Sleep(3000);
UnityThread.Instance.EnqueueTask(() => Debug.Log($"Data received: {data}"));
});
backgroundThread.Start();
}Unity Unity3D UnityThreading Threading Multithreading Async Coroutine UnityCoroutines BackgroundTasks GameDevelopment UnityTools GameOptimization UnityPerformance UnityAPI CSharp UnityEngine TaskQueue Concurrency PerformanceOptimization UnityUtilities