Yield WaitForSeconds + Instantiate problems

Hello. First of all I understand (sorta) where i am going wrong with this, i just don’t possess the knowledge to correct it.

I have a function where, after few seconds (random) it spawns an enemy. Problem, in between this random range, it doesn’t stop spawning enemies. The idea is that between 5-10 seconds, it spawns enemies. Not, wait until then and then don’t stop spawning.

function spawnEnemy ()
{
yield WaitForSeconds(Random.Range(spawnStartTime,spawnStopTime));
Instantiate(enemySquare,transform.position,transform.rotation);
Instantiate(enemyCircle,transform.position,transform.rotation);
}

This is the first thing i am calling in my “Function Update ()”, should it be somewhere else, maybe?

Thanks guys

I wouldn’t call this in Fixed Update. If you are going to have a spawning system you would be better off using something like this…

public float spawnTiming = 10.0f;
public float spawnTimer = 0.0f;

void Update()
{
     spawnTimer += Time.deltaTime;
     if(spawnTimer > spawnTiming)
     {
          spawnTimer = 0;
          // spawn code here
      }
}

What you called is really only used for calling the function once like in start or a button click. after it has waited for x amount of seconds the valve will always be true, this what is causing your repeat spawning and most likely will cause Unity to crash.

is that C#, i’m really only using JS, so it isn’t making a lot of sense to me. Sorry.

var spawnTiming : float = 10;
var spawnTimer : float = 0;


function Update () {
    spawnTimer += Time.deltaTime;

    if(spawnTimer > spawnTiming)
    {
        spawnTimer = 0;
        // spawn code here
    }
}

There ya go, you should though learn to read one and convert it to the other since most of the examples are not written in JS. But I hope this helps!

Thankyou. That works perfectly now =]