Display progress in a long loop in Unity3d -
i'm building space game, populated thousands of star systems. right now, there function generates these thousands of systems. takes 5-10 seconds generate, , have simple progress bar updating user in progress.
after searching i've decided use coroutine, there little problem: when call function generate star systems, code called function keeps on going, reporting 0 stars (because haven't been generated yet).
i have feeling coroutines not answer me. basically, looking way simulate application.doevents update gui.
here sample of code:
// start generating thousands of systems startcoroutine(galacticmap.generaterandomgalaxy()); // after universe generated... game.mygalaxy.starsystems = galacticmap.mygalaxy.starsystems; // report number of systems print(string.format("generated {0} systems", game.mygalaxy.starsystems.count));
in galacticmap.generaterandomgalaxy()
yielding yield return new waitforseconds(0.1f);
however, effect not looking for: execution goes right through print
statement while generation still on going.
so how do this?
edit 1:
i've cooked sample code illustrate issue.
the caller code:
debug.log ("start generating"); startcoroutine(generatemegalaxy()); debug.log ("finish generating");
the code call:
public static ienumerator generatemegalaxy () { debug.log ("generatemegalaxy start"); int numberofstars = 1000; (int i=0;i<=numberofstars;i++) { // generate galaxy // display progress bar on screen debug.monitor(string.format("{0}% completed", ((i*100)/numberofstars)),2); yield return new waitforseconds(0.001f); } debug.log ("generatemegalaxy end"); }
in code above, debug.log
displays string on screen, on new line can read previous logged strings of whatever. debug code execution. debug.monitor
has fixed location on screen , overwrite previous string. display progress percentage. see after running code is:
start generating generatemegalaxy start finish generating generatemegalaxy end
what want see is:
start generating generatemegalaxy start generatemegalaxy end finish generating
... , progress update happening in between:
generatemegalaxy start finish generating
i think misunderstanding how unity coroutines work. yield return new waitforseconds(0.1f)
saying "go other stuff , come me after 0.1 second". naturally unity go ahead , other stuff, including print statement.
what want along lines of following pattern:
ienumerator generaterandomgalaxy() { int numsystems = 5000; // many systems want generate foreach(int = 0; < numsystems; i++) { // insert code here generates system // insert code here updates progress bar yield return null; } // put logic prints out final number of systems generated here }
what generate system, update status bar, , -- yield return null
statement -- tell unity take on (so other stuff, including rendering updated progress bar) , come , continue loop possible.
finally, print statement happens after loop finished, intend.
Comments
Post a Comment