c# - 如何赋予方法处理 Unity 中另一个线程的对象的能力
问题描述
我有一个通过访问舞台上的对象来工作的库,我需要一些我在另一个线程中调用的方法可以在舞台上做某事的东西,我将非常感谢您的帮助。
我正在使用任务类
return Task.Run(() =>
{
// My method in library
});
解决方案
您不能从主线程外部修改 Unity 对象。因此,如果您的任务需要修改 Unity 对象,则需要从主线程中获取 SynchronizationContext 并使用它来将工作发布或发送回主线程,以进行实际的统一对象修改和引用。
// make sure you are on the main thread when you call this next line.
SynchronizationContext mainThreadSyncContext = SynchronizationContext.Current;
Task.Run(() => {
// do heavy work
// then when you want to modify a unity object or referenc them, you have to delegate the work to run
// on the main thread.
mainThreadSyncContext.Post(_ => {
// async so it does not block and the work will be executed at some point (most likely the next tick)
// safely reference Unity objects and functions
}, null);
mainThreadSyncContext.Send(_ => {
// synchronous so it will send the the main thread and wait for a return before continuing
// safely reference Unity objects and functions
}, null);
});