46 lines
1.1 KiB
C#
46 lines
1.1 KiB
C#
using System;
|
|
using System.Collections.Concurrent;
|
|
using UnityEngine;
|
|
|
|
public class UnityMainThreadDispatcher : MonoBehaviour
|
|
{
|
|
private static readonly ConcurrentQueue<Action> _executionQueue = new ConcurrentQueue<Action>();
|
|
|
|
private static UnityMainThreadDispatcher _instance;
|
|
|
|
public static void Initialize()
|
|
{
|
|
if (_instance == null)
|
|
{
|
|
GameObject obj = new GameObject("UnityMainThreadDispatcher");
|
|
_instance = obj.AddComponent<UnityMainThreadDispatcher>();
|
|
DontDestroyOnLoad(obj);
|
|
}
|
|
}
|
|
|
|
public static UnityMainThreadDispatcher Instance()
|
|
{
|
|
if (_instance == null)
|
|
{
|
|
throw new Exception("UnityMainThreadDispatcher is not initialized. Call UnityMainThreadDispatcher.Initialize() first.");
|
|
}
|
|
return _instance;
|
|
}
|
|
|
|
public void Enqueue(Action action)
|
|
{
|
|
_executionQueue.Enqueue(action);
|
|
}
|
|
|
|
void Update()
|
|
{
|
|
while (_executionQueue.Count > 0)
|
|
{
|
|
if(_executionQueue.TryDequeue(out var action))
|
|
{
|
|
action.Invoke();
|
|
}
|
|
}
|
|
}
|
|
}
|