69 lines
1.6 KiB
C#
69 lines
1.6 KiB
C#
|
#if UNITY_EDITOR
|
||
|
|
||
|
using System;
|
||
|
using System.Collections;
|
||
|
using System.Collections.Generic;
|
||
|
using UnityEngine;
|
||
|
|
||
|
namespace UguiToolkit.Editor
|
||
|
{
|
||
|
[ExecuteAlways]
|
||
|
public class UnityMainThreadDispatcher : MonoBehaviour
|
||
|
{
|
||
|
private static readonly Queue<Action> _executionQueue = new Queue<Action>();
|
||
|
|
||
|
private static UnityMainThreadDispatcher _instance = null;
|
||
|
|
||
|
public static UnityMainThreadDispatcher Instance()
|
||
|
{
|
||
|
if (!_instance)
|
||
|
{
|
||
|
_instance = FindObjectOfType<UnityMainThreadDispatcher>();
|
||
|
if (!_instance)
|
||
|
{
|
||
|
var obj = new GameObject("UnityMainThreadDispatcher");
|
||
|
_instance = obj.AddComponent<UnityMainThreadDispatcher>();
|
||
|
}
|
||
|
}
|
||
|
return _instance;
|
||
|
}
|
||
|
|
||
|
private void Update()
|
||
|
{
|
||
|
lock (_executionQueue)
|
||
|
{
|
||
|
while (_executionQueue.Count > 0)
|
||
|
{
|
||
|
_executionQueue.Dequeue().Invoke();
|
||
|
}
|
||
|
}
|
||
|
}
|
||
|
|
||
|
public void Enqueue(IEnumerator action)
|
||
|
{
|
||
|
lock (_executionQueue)
|
||
|
{
|
||
|
_executionQueue.Enqueue(() => { StartCoroutine(action); });
|
||
|
}
|
||
|
}
|
||
|
|
||
|
public void Enqueue(Action action)
|
||
|
{
|
||
|
Enqueue(ActionWrapper(action));
|
||
|
}
|
||
|
|
||
|
IEnumerator ActionWrapper(Action a)
|
||
|
{
|
||
|
a();
|
||
|
yield return null;
|
||
|
}
|
||
|
|
||
|
public static void EnqueueMainThread(Action action)
|
||
|
{
|
||
|
Instance().Enqueue(action);
|
||
|
}
|
||
|
}
|
||
|
}
|
||
|
|
||
|
#endif
|