0

I have the following code...

StartCoroutine(GetSuggestions()); IEnumerator GetSuggestions() { longExecutionFunction(); // this takes a long time yield return null; } 

How can I use a coroutine to keep the main program flow going? Currently when it reaches longExecutionFunction(); the program stops for a few seconds. I'd like it if the whole program would keep working while this is going on. How can I do this?

3 Answers 3

2

Without using threads, assuming you can modify longExecutionFunction, and it looks something like this:

void longExecutionFunction() { mediumExecutionFunction(); mediumExecutionFunction(); while(working) { mediumExecutionFunction(); } } 

You could modify it to look like:

IEnumerator longExecutionFunction() { mediumExecutionFunction(); yield return null; mediumExecutionFunction(); yield return null; while(working) { mediumExecutionFunction(); yield return null; } } 

Then modify the calling code something like:

StartCoroutine(GetSuggestions()); IEnumerator GetSuggestions() { yield return longExecutionFunction(); //all done! } 

This would then do one "medium length thing" per update, keeping the game from hanging. If, and how finely you can break up the work inside longExecutionFunction depends on your code inside it.

Sign up to request clarification or add additional context in comments.

Comments

0

You would need to start longExecutionFunction in another thread. You may want to look at this article to read about threading: http://msdn.microsoft.com/en-us/library/system.threading.thread.aspx

Code Example:

var thread = new System.Threading.Thread(new System.Threading.ThreadStart(() => { longExecutionFunction(); })); thread.Start(); 

If you aren't familiar with threads you should read up on them before using them. :)

2 Comments

Unity game engine is not thread safe and it is strongly recommended to not use threads
Is this not doable with a coroutine?
0

You should use Threads combined with a coroutine.

StartCoroutine(MyCoroutine()); [...] IEnumerator MyCoroutine() { Thread thread = new Thread(() => { longExecutionFunction(); }); thread.Start(); while (thread.IsAlive) yield return 0; // ... Use data here } 

However you cannot use any unity-objects or methods inside the longExecutionFunction, because unity is not thread safe. So you need to calculate all your data inside the longExecutionFunction and initialize unity objects when the method has returned.

3 Comments

AFAIK you cannot create threads in web player, so even if longExecutionFunction() didn't touch unity objects it would still restrict the platform.
@MikeMcFarland forum.unity3d.com/threads/76087-WebPlayer-Multi-threading This links tells something else.
Awesome, thanks for the correction. It's good to know its possible.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.