- Home /
Start to Update() after X seconds
Hi everybody... I have a question:
I'm creating a Tower Defense game in Unity and I'm doing the wave control now.
I want to start the wave object's update after X seconds, like most of the Tower Defense games we see.
Example:
My game starts and all the monsters coming from the first wave are released.
After the first wave is done I disable it and enable the second wave. And then I want that the second wave start to update (because it is in the Update method that I control all the monsters) after a pre-determined time.
How can I do this?
I'm open for any suggestions.
Thanks in advance.
You simply need to learn about the "Invoke" command. Nothing to it ....
Answer by syclamoth · Jan 23, 2012 at 03:03 PM
Try shifting all the logic you would usually put in Update into a coroutine that gets set off by Start. That way, you can put a
yield WaitForSeconds(x seconds);
before beginning on the rest of the logic! There is no way to actaully delay the Update function without freezing the entire game- but there are plenty of ways to achieve what you are trying to do without doing that.
Answer by Statement · Jan 23, 2012 at 04:24 PM
I prefer coroutines for tasks like these.
Start()Your starting point that will run 3 waves of monsters. After for loop, show a victory screen for example.BeginWave(var wave : int)Put setup code for the wave there, like spawning enemies or changing the music.RunWave(var wave : int)Put update code the wave inside the while loop. Remember toyield;or it crash.EndWave(var wave : int)Put cleanup code for the wave there, like removing enemies or changing the music.
The WaitForSeconds are optional and was only meant to illustrate how you can delay the code at various points.
function Start() {
for (var wave = 0; wave < 3; ++wave) {
yield BeginWave(wave);
yield RunWave(wave);
yield EndWave(wave);
}
}
function BeginWave(var wave : int) {
// Set up the wave, if needed...
yield WaitForSeconds(5);
}
function RunWave(var wave : int) {
while (true) {
// Update your game logic as before.
// 'break;' (or 'yield break;' if in nested loop) to end wave.
yield;
}
}
function EndWave(var wave : int) {
// Clean up the wave, if needed...
yield WaitForSeconds(5);
}
Or if you are more of a compact code fan (I'm not):
function Start() {
for (var wave = 0; wave < 3; ++wave) {
// Set up the wave, if needed...
yield WaitForSeconds(5);
while (true) {
// Update your game logic as before.
// 'break;' to end wave.
yield;
}
// Clean up the wave, if needed...
yield WaitForSeconds(5);
}
}
I use the same coroutine trick, but create a prefab with a "spawn script" on it. When the player presses begin, instantiate the spawn script for that level. It waits 3 secs, spawns a wave, waits more, then spawns the other two waves on the level.
It hurts my head to have the level logic (level preview, help menu, You lose -- retry?) in the same script as the level.
Your answer