52 lines
1.4 KiB
C#
52 lines
1.4 KiB
C#
using System;
|
|
using System.Collections.Generic;
|
|
using UnityEngine;
|
|
|
|
public class UnityMainThreadDispatcher : MonoBehaviour
|
|
{
|
|
private static UnityMainThreadDispatcher _instance;
|
|
private readonly Queue<Action> _actionQueue = new Queue<Action>();
|
|
|
|
// 获取单例实例
|
|
public static UnityMainThreadDispatcher Instance
|
|
{
|
|
get
|
|
{
|
|
if (_instance == null)
|
|
{
|
|
// 查找现有实例
|
|
_instance = FindObjectOfType<UnityMainThreadDispatcher>();
|
|
|
|
// 如果没有实例则创建一个
|
|
if (_instance == null)
|
|
{
|
|
GameObject obj = new GameObject("UnityMainThreadDispatcher");
|
|
_instance = obj.AddComponent<UnityMainThreadDispatcher>();
|
|
DontDestroyOnLoad(obj); // 跨场景保留
|
|
}
|
|
}
|
|
return _instance;
|
|
}
|
|
}
|
|
|
|
private void Update()
|
|
{
|
|
// 每帧执行队列中的所有回调(在主线程)
|
|
lock (_actionQueue)
|
|
{
|
|
while (_actionQueue.Count > 0)
|
|
{
|
|
_actionQueue.Dequeue().Invoke();
|
|
}
|
|
}
|
|
}
|
|
|
|
// 将行动添加到主线程执行队列
|
|
public void Enqueue(Action action)
|
|
{
|
|
lock (_actionQueue)
|
|
{
|
|
_actionQueue.Enqueue(action);
|
|
}
|
|
}
|
|
} |