using System; using System.Collections; using System.Collections.Generic; using UnityEngine; public class ThreadManager : MonoBehaviour { private static readonly List executeOnMainThread = new List(); private static readonly List executeCopiedOnMainThread = new List(); private static bool actionToExecuteOnMainThread = false; private void FixedUpdate() { UpdateMain(); } /// Sets an action to be executed on the main thread. /// The action to be executed on the main thread. public static void ExecuteOnMainThread(Action _action) { if (_action == null) { Console.WriteLine("No action to execute on main thread!"); return; } lock (executeOnMainThread) { executeOnMainThread.Add(_action); actionToExecuteOnMainThread = true; } } /// Executes all code meant to run on the main thread. NOTE: Call this ONLY from the main thread. public static void UpdateMain() { if (actionToExecuteOnMainThread) { executeCopiedOnMainThread.Clear(); lock (executeOnMainThread) { executeCopiedOnMainThread.AddRange(executeOnMainThread); executeOnMainThread.Clear(); actionToExecuteOnMainThread = false; } for (int i = 0; i < executeCopiedOnMainThread.Count; i++) { executeCopiedOnMainThread[i](); } } } }