Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
86 views
in Technique[技术] by (71.8m points)

c# - Wait for UnityMainThreadDispatcher to return Unity

I'm trying to move my pathfinding over to a separate thread. But I still have 1 function that I need to call from the Main thread at each node in the search. I found the UnityMainThreadDispatcher here which aims to fix this problem by running the given action on the main thread. However, I can't continue in my function until I have the value returned from this action. Here is the code that i'm currently trying to make work.. When I debug this code, a valid returnVal is returned in the callback, but when I try and wait for this value, i.e. by using a while loop, I get stuck in an infinite loop. Why is this?

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

I know this isn't good to do, what can I do instead? Thank you

question from:https://stackoverflow.com/questions/65909267/wait-for-unitymainthreaddispatcher-to-return-unity

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I've tried a few different Unity multiple thread plugins and haven't had great experiences. I'm not saying "UnityMainThreadDispatcher" can't be a good solution, but it seems like running Unity specific functionality on multiple threads would be a smoother, better documented process if the Unity team tackled it. Also, it's good to avoid including extra plugins if you can help it. That said:

Depending on the contents of your one "function that I need to call from the main thread", you could slice up your code into more modular pieces and make that main thread call in between firing async tasks. For example, I have a process heavy task that requires a loading bar for the user. I create a global variable that an await Task.Run() builds on, then I make updates/retrieve data from the Unity API on the main thread (including updating the progress bar), and then I go into the next await Task.Run().


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...