Before updating to Windows 10 you may need to return your Pro license. More information here

Timer to call Instantiate

I've been coding a game where a player must avoid random enemies as they reach him and have written the code to wait a set amount of time before spawning the next enemy. I have a counter in the Update function that should call the random generator function and reset itself when it reaches a certain threshold, however when I run the program it decides to ignore the if statement and execute everything in the Update function every frame. How can I fix this?

 var waitTime: float = 100;
 var counter : float = 0;
 function Update () {
     //counts up every frame
     print(counter); //temp
     //calls enemySpawn when the limit is reached  
     //resets the counter
     if (counter >= waitTime){
         counter = 0;
more ▼

asked Feb 10, 2012 at 12:35 AM

avatar image

1 3 2 3

(comments are locked)
10|3000 characters needed characters left

1 answer: sort voted first

For that kind of things, coroutines are just per-fect. Basically, they allow you to stop the execution of a function for a given amount of time, letting the rest of the program run, and then finishing when the time as past. Here is what you can do :

 function Start(){
 function Spawn(){
     while( true ){
         yield WaitForSeconds(waitTime); // That line tell the function to stop for waitTime seconds
more ▼

answered Feb 10, 2012 at 12:40 AM

avatar image

13.9k 47 52 119

Thank you that works great :D I'm still having a problem though. The scene works fine at the start but as time goes on, the time between spawns decreases to the point where the enemies are overlapping each other. It is as if something keeps calling the script over and over again or something. Any ideas?

Feb 10, 2012 at 12:51 AM Lawzer

Make sure you don't call the function Spawn in Update. It must be call only once. In C#, as what's going is less hidden, I think it's more obvious. Instead of Spawn(), it would be StartCoroutine( Spawn() ), making it clear that you create a new instance of the coroutine. So yeah, call it only once ^^

Feb 10, 2012 at 01:21 AM Berenger

I think I was calling it twice in the scene, though I can't be sure. I realised that I could merge my working player script with this level one with ease as I will always have the player onscreen. Now it all works great. Thanks for your help :)

Feb 10, 2012 at 01:57 AM Lawzer
(comments are locked)
10|3000 characters needed characters left
Your answer
toggle preview:

Up to 2 attachments (including images) can be used with a maximum of 524.3 kB each and 1.0 MB total.

Follow this question

By Email:

Once you sign in you will be able to subscribe for any updates here



Answers and Comments



asked: Feb 10, 2012 at 12:35 AM

Seen: 1698 times

Last Updated: Feb 10, 2012 at 01:57 AM