- Home /
Increasing spawn rate over time
I want to create an enemy that spawn when the level starts and then increase over time. However, with the code I have right now the objects will never actually appear in my game. And if I move the Instantiate to if(spawnTime == 0) then two of each object will spawn (only 1 of each should).
var spawnTime : float = 0; var timeIncrease : int = 0; var Enemy: Transform; var Enemy2:Transform;
function Update(){ if(spawnTime == 0){ timeIncrease = Time.time; spawnTime = Time.time; }
if(spawnTime == 10){
Instantiate(Enemy,transform.position,transform.rotation);
Instantiate(Enemy2,transform.position,transform.rotation);
spawnTime = 0;
}
if(timeIncrease == 30){
timeIncrease = 0;
spawnTime = -0.5;
}
}
Answer by xCRKx TyPHooN · Apr 06, 2011 at 09:18 PM
SpawnTime is a float and you are comparing it to an int which isn't a good practice. Because spawnTime is a float and is incrementing based on the built in time class, its never going to be exactly equal to 10, therefore, it will never Instantiate your new objects. You could use a typecast to fix this, but its probably best to rewrite your code so you can keep the precision required with time.
Well if I modify my code to compare to float times (<= & >=) then it leaves the possibility of it spawning twice very quickly. Is there a way to do it while spawnTime is an integer?
Also is there a way to have the objects spawn right when the level loads, but then not again until 10 seconds later?
Use a bool and when it hits the spawn timer first at 10 seconds flip a flag so it can't hit it again. You can spawn an object in the Awake() function, as it's called only one.