- Home /
Spawn object with time difference
So we are making this fish game where a bunch of "Enemy fish" will appear on the screen from the right side and the Player fish will have to avoid them by moving up & down. Now the problem occurs when we are trying to spawn those enemy fishes.
void SpawnEnemy(){
Instantiate(prefab, new Vector3(25, Random.Range(1,20), 0), Quaternion.identity);
}
int NextEnemySpawnTime = 0;
int EnemySpawnRate = 5;
void Update(){
if((int)Time.time == NextEnemySpawnTime)){
SpawnEnemy();
NextEnemySpawnTime = (int)Time.time + EnemySpawnRate;
}
}
The idea was to create enemy fish every five seconds, but when we run this a whole bunch of cubes (enemy fishes) floods the screen. How can we make the Update function to call SpawnEnemy() function exactly every five seconds? We're bunch of newbies, any help/suggestion is appreciated.
Answer by blackcloud1971 · Sep 29, 2013 at 07:11 PM
Ok so the problem was I was attaching this script to the object I wanted to re-spawn. So it was creating a copy of itself and that copy was making a copy and so on.... this was like a chain reaction, hence I ended up with lots of objects than I meant to.
To fix this problem I created an Empty object and attached this script to that Empty Object fixed the problem :)
Answer by robertbu · Sep 27, 2013 at 01:46 AM
The easiest way to solve your problem would be to use InvokeRepeating(). In Start(), just do:
InvokeRepeating("SpawnEnemy", 0.0f, 5.0f);
You don't need any of the code you are currently using in Update() if you use InvokeRepeating().
that was actually helpful, but I had to call my SpawnEnemy inside Update for other purposes, thx tho
Your answer
