- Home /
How to instantiate prefabs in an unloaded (or just loaded) scene?
So I'm very new to Unity3D and just recently started work on my first, true, large-scale game. Thanks to the wonderful tutorial at BugZergArcade, my time has been very well spent and I've been learning quickly.
To avoid the need for artists and still allow for unlimited gameplay, I wished to implement procedural level generation. This is where the tutorials fell short. They don't have anything on world generation.
When I looked into how to make a script run at start-up the official recommendation seems to be to have an empty GameObject in the world, then attach the script to this. I foresee one of two possible problems with this, however.
If the scripts run in parallel then the player may be able to move around or fall through the world before it's finished generating
If the scripts run in series then I won't be able to update the GUI as the world generates, which means no "loading bars"
Does anyone have a solution for this, or are my two worries simply unfounded? Ultimately I want the final effect to be: User starts game, user sees main menu, user hits play, user sees a loading screen, user is placed in a random world.
Answer by Owen-Reynolds · May 27, 2013 at 01:51 AM
Can use a coroutine to spread out world generation over a few frames. Do about 1/4 second's worth of work, then yield for a frame. Sort of an odd system. The trick is that nothing happens while you are doing work. No frames, no drawing, no timer changing. So each frame happens when you yield.
For the player, just give the player a Paused variable. You'll probably have one anyway, for menus (or the Pause key?) Set to true when done making the level. Or you could spawn the player last (most people would have the players pre-spawned.)
This sounds like the perfect solution. How do I make a coroutine, though? Do I just insert an empty GameObject with the world generation code and sprinkle it with yield
occasionally?
However you have the world-making code would be the same with/without a coroutine. So, yes, I have a generator function where I just "sprinkled" in a yield. The script on an empty is fine. Then just look up Coroutine in the standard docs.
Besides putting in an occasional yield return null;
(let someone else have a turn; resume from here next frame,) you'd call with StartCoroutine and have to use the IEnumerator return type. But coroutines are a popular topic. Lots of examples here.
Your answer
Follow this Question
Related Questions
Occlusion culling world generation runtime 0 Answers
For loop not starting from zero 0 Answers
Optimizing Procedural terrain 2 Answers
Procedural pathfinding 0 Answers
How can I represent different biomes on a Terrain object? 0 Answers