创建脚本UnityMainThreadDispatcher.cs
using System;
using System.Collections.Generic;
using UnityEngine;
public class UnityMainThreadDispatcher : MonoBehaviour
{
private static readonly Queue<Action> _executionQueue = new Queue<Action>();
public static void Enqueue(Action action)
{
lock (_executionQueue)
{
_executionQueue.Enqueue(action);
}
}
private void Update()
{
lock (_executionQueue)
{
while (_executionQueue.Count > 0)
{
_executionQueue.Dequeue().Invoke();
}
}
}
}
然后把这个脚本挂载到你需要调用线程的scene场景里,随便挂载哪里都可以,挂在主相机上也可以。
在你自己代码线程中需要调用API或者某些需要在主函数执行的报错匿名函数包起来就能正常调用方法了。
....
UnityMainThreadDispatcher.Enqueue(()=> {
//例如gameobject.SetActive(false);
});