Company logo
  • Jobs
  • Bootcamp
  • About Us
  • For professionals
    • Home
    • Jobs
    • Courses
    • Questions
    • Teachers
    • Bootcamp
  • For business
    • Home
    • Our process
    • Plans
    • Assessments
    • Payroll
    • Blog
    • Calculator

0

117
Views
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

9 months ago · Santiago Trujillo
1 answers
Answer question

0

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().

9 months ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post job Plans Our process Sales
Legal
Terms and conditions Privacy policy
© 2023 PeakU Inc. All Rights Reserved.