Spawning too many enemies.

Im trying to spawn enemies but everytime i do it spawns too many and unity will crash this is my code.

var enemy : GameObject;
while(true){
Instantiate(enemy,transform.position,transform.rotation);
yield WaitForSeconds(6);
}

Considering you have a static variable for the counting of the enemy and you increment the variable each time you instantiate an enemy. If you only want 10 enemies and one each 5 seconds (starting after 2seconds):

static var count:int;
function Start(){
   count = 0; 
   InvokeRepeating("SpawnEnemy", 2.0f,5.0f);
}
function Update(){
   if(count>= 10)CancelInvoke();
}
function SpawnEnemy(){
   Instantiate(enemy,transform.position,transform.rotation);
   count++;
}

Here is the documentation about InvokeRepeating: Unity - Scripting API: MonoBehaviour.InvokeRepeating

if you need to stop the spawning use CancelInvoke:

If you CancelInvoke() isn’t it going to stop indefinitely so what you want is either to start it back up when count < 3 or a recursive invoke or a test on spawn i.e.

(Please note in the examples below the call to Invoke may not be right I am working from memory and am a C# dev week in Java)

static var count:int;
function Start(){
  count = 0; 
  InvokeRepeating("SpawnEnemy", 2.0f,2.0f);
}
function Update(){

}
function SpawnEnemy(){
  if(count < 3){
  count++;
  print(count);
  }
}

or

static var count:int;
function Start(){
  count = 0; 
  Invoke("SpawnEnemy", 2.0f,2.0f);
}
function Update(){
}
function SpawnEnemy(){
  count++;
  print(count);

  if(count < 3){
  Invoke("SpawnEnemy", 2.0f,2.0f);
  }
}

or

static var count:int;
  static var Spawning : bool
function Start(){
  count = 0; 
  InvokeRepeating("SpawnEnemy", 2.0f,2.0f);
}
function Update(){
  if(count>= 3)
    CancelInvoke();
  else if(!Spawning)
    InvokeRepeating("SpawnEnemy", 2.0f,2.0f);
}
function SpawnEnemy(){
  count++;
  print(count);
}