using UnityEngine; using System.Collections.Generic; using System; public class UnityMainThreadDispatcher : MonoBehaviour { private static readonly Queue _executionQueue = new Queue(); public static UnityMainThreadDispatcher Instance { get; private set; } void Awake() { if (Instance == null) { Instance = this; DontDestroyOnLoad(this.gameObject); } } void Update() { lock (_executionQueue) { while (_executionQueue.Count > 0) { _executionQueue.Dequeue().Invoke(); } } } public void Enqueue(Action action) { lock (_executionQueue) { _executionQueue.Enqueue(action); } } }