【问题标题】:Wait for UnityMainThreadDispatcher to return Unity等待 UnityMainThreadDispatcher 返回 Unity
【发布时间】:2021-04-30 16:54:30
【问题描述】:

我正在尝试将我的寻路转移到一个单独的线程。但我仍然有 1 个函数需要从搜索中每个节点的主线程调用。我找到了 UnityMainThreadDispatcher here,它旨在通过在主线程上运行给定的操作来解决这个问题。但是,在我从该操作返回值之前,我无法继续执行我的函数。 这是我目前正在尝试使用的代码。当我调试此代码时,回调中会返回一个有效的 returnVal,但是当我尝试等待该值时,即使用 while 循环时,我被卡住了在无限循环中。这是为什么呢?

var latlon = Vector2d.zero;

UnityMainThreadDispatcher.Instance().Enqueue(() =>
{
    Debug.Log("Running on Main thread");
    _monoBehaviour.StartCoroutine(
        GetLatLonFromUnityCoords(point, returnVal => 
            {
                    latlon = returnVal;
                    Debug.Log($"Calculated latlon: {latlon}");
            }
    ));
    Debug.Log("Finished on Main thread");
});

while (latlon = Vector2d.zero) { }

// latlon has been returned, continue

我知道这样做不好,我能做些什么呢? 谢谢

【问题讨论】:

    标签: c# multithreading unity3d coroutine


    【解决方案1】:

    我尝试了几个不同的 Unity 多线程插件,但体验并不好。我并不是说“UnityMainThreadDispatcher”不是一个好的解决方案,但如果 Unity 团队解决了这个问题,在多个线程上运行 Unity 特定功能似乎会是一个更顺畅、更好记录的过程。此外,如果可以提供帮助,最好避免包含额外的插件。也就是说:

    根据你的一个“我需要从主线程调用的函数”的内容,你可以将你的代码分割成更模块化的部分,并在触发异步任务之间进行主线程调用。例如,我有一个需要为用户加载栏的繁重任务。我创建了一个构建 await Task.Run() 的全局变量,然后在主线程上从 Unity API 更新/检索数据(包括更新进度条),然后进入下一个 await Task.Run()

    【讨论】:

      猜你喜欢
      • 2013-02-18
      • 2014-06-30
      • 2020-03-13
      • 1970-01-01
      • 2017-11-09
      • 1970-01-01
      • 2014-10-06
      • 2013-05-13
      • 2020-02-15
      相关资源
      最近更新 更多