How do I spawn enemies based on a timer?

Hey, I want to make a very simple enemy spawner, for a 2D game, but I’m new to Unity3D and I;m not sure how to go about doing it. I have 4 prefabs, named spawn1, spawn2, spawn3 and spawn4 - 2 of which are located on the left of the screen, 2 on the right. Here is the code on the prefab:

var enemySpeed: int;

function Update () {

amtToMove = enemySpeed * Time.deltaTime;

transform.Translate(Vector3.left * amtToMove);
//transform.Translate(Vector3.right * amtToMove);  - for the prefabs on the left of the screen

}

I have a timer that counts down for 120 seconds, which uses the variables displayMinutes and displaySeconds. I want each of the prefabs to spawn a new enemy every 3 seconds. Is there a way I can do this?

Thanks in advance! :smiley:

1 Answer

1

Of course there is a way to do this:

Intead of having a countdown timer, which is quite innacurate and slow, you could just save the time you want the enemy to spawn and compare it to the current time (Time.time)

var Enemy:Transform;
private var Timer:float;

function Awake() {
    Timer = Time.time + 3;
}

function Update() {
    if (Timer < Time.time) { //This checks wether real time has caught up to the timer
        Instantiate(Enemy, transform.position, transform.rotation); //This spawns the emeny
        Timer = Time.time + 3; //This sets the timer 3 seconds into the future
    }
}

Of course you could make things more random and other stuff, but this will spawn an enemy every 3 seconds.

I'll test this later, thanks for the reply!

This does work, but it spawns hundreds of the enemies instantly D:

Ive edited the answer to include a possible fix??? Plz tell me if it works :)

That works perfectly! Thank you very much!

If my answer is correct please accept it as the answer :)