在Unity中,可以通过以下方法在后台线程中调用主线程中的函数:
using UnityEngine;
// 在后台线程中调用主线程函数的类
public class MainThreadCaller : MonoBehaviour
{
private static MainThreadCaller instance;
private void Awake()
{
// 确保只有一个实例存在
if (instance != null && instance != this)
{
Destroy(this.gameObject);
}
else
{
instance = this;
DontDestroyOnLoad(this.gameObject);
}
}
// 在主线程中调用函数
public void CallMainThreadFunction(System.Action function)
{
if (function != null)
{
UnityMainThreadDispatcher.Instance().Enqueue(function);
}
}
}
// 在主线程中调用函数的调度器
public class UnityMainThreadDispatcher : MonoBehaviour
{
private static UnityMainThreadDispatcher instance;
private readonly Queue<System.Action> actionQueue = new Queue<System.Action>();
public static UnityMainThreadDispatcher Instance()
{
if (instance == null)
{
instance = FindObjectOfType<UnityMainThreadDispatcher>();
if (instance == null)
{
GameObject go = new GameObject("UnityMainThreadDispatcher");
instance = go.AddComponent<UnityMainThreadDispatcher>();
}
}
return instance;
}
private void Update()
{
lock (actionQueue)
{
while (actionQueue.Count > 0)
{
System.Action action = actionQueue.Dequeue();
action?.Invoke();
}
}
}
public void Enqueue(System.Action action)
{
lock (actionQueue)
{
actionQueue.Enqueue(action);
}
}
}
然后,在后台线程中使用以下代码调用主线程函数:
MainThreadCaller.Instance().CallMainThreadFunction(() =>
{
// 在主线程中调用的函数
YourFunction();
});
using UnityEngine;
public class YourClass : MonoBehaviour
{
private void Start()
{
// 在后台线程中调用主线程函数
StartCoroutine(CallMainThreadFunction(() =>
{
// 在主线程中调用的函数
YourFunction();
}));
}
// 在后台线程中等待一帧后调用主线程函数
private System.Collections.IEnumerator CallMainThreadFunction(System.Action function)
{
yield return null; // 等待一帧
function?.Invoke(); // 调用主线程函数
}
}
以上两种方法都可以实现在Unity中通过后台线程调用主线程中的函数。其中,方法1使用了Unity的主线程调度器,方法2使用了Coroutine等待一帧后执行。这些方法在多线程编程中非常有用,可以提高程序的效率和响应性。
领取专属 10元无门槛券
手把手带您无忧上云