Skip to content

Instantly share code, notes, and snippets.

@inoook
Created July 10, 2023 06:13
Show Gist options
  • Save inoook/8a0ad3083c7967df14083892fd91b33a to your computer and use it in GitHub Desktop.
Save inoook/8a0ad3083c7967df14083892fd91b33a to your computer and use it in GitHub Desktop.
using UnityEngine;
using System.Collections.Generic;
public class MainThreadDispatcher : MonoBehaviour
{
private static MainThreadDispatcher instance;
private static readonly object lockObject = new object();
private Queue<System.Action> actions = new Queue<System.Action>();
void Update()
{
lock (lockObject)
{
while (actions.Count > 0)
{
System.Action action = actions.Dequeue();
action.Invoke();
}
}
}
public static MainThreadDispatcher Instance()
{
if (instance == null)
{
GameObject go = new GameObject("MainThreadDispatcher");
instance = go.AddComponent<MainThreadDispatcher>();
}
return instance;
}
public void Invoke(System.Action action)
{
lock (lockObject)
{
actions.Enqueue(action);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment