How do I only clone 1 enemy instead of infinity enemies??

I made a script, and when the timer reaches 0 I want it to only spawn 1 enemy but it keeps spawning.
What do I add to the script pls help.

var timer : float = 10.0;
var enemy : Rigidbody;
var sound : AudioClip;

function Update () {

timer -= Time.deltaTime;

if(timer <= 0)
{
    var clone : Rigidbody;
	clone = Instantiate(enemy, transform.position, transform.rotation);
	clone.velocity = transform.TransformDirection (Vector3.forward);
	AudioSource.PlayClipAtPoint(sound, transform.position, 1);
}

}

You could add a bool value to stop the spawning:

if ( timer <= 0 && spawned == false)
{
    ...
    spawned = true;
}

The reason why its continueing to spawn enimies is for 2 major factors.

  1. You have this running in Update, so itll check your if-statement every frame.

  2. Because of that, your if-statement itself, is checking if your timer is less or equal to 0… And you never reset your timer at any point, so it continues to count beyond zero, and any negative number is less or equal to zero…

You can fix this with 3 ways.

  1. Create a variable, call it something like “allowSpawn” set it to true at the start. Once a enemy is spawned, after your audio line, add: allowSpawn = false;, now surround your entire if-statement in another if-statement that would read: if(allowSpawn == true){//your timer if-statement}

  2. Change your if-statement to read if(timer == 0) instead, so only when it hits 0 it will spawn - realistically itll still continue to count down, but it wont continue to spawn things until it reaches 0 again, which it never will since you never reset the tmer.

  3. Reset your timer back to 10 seconds again, so after your audio line, youd add timer = 10.0; - now this means 1 enemy will spawn every 10 seconds… If you only want 1 enemy to spawn ever, after 10 seconds, use Invoke instead.