- Home /
Array index out of Range
Hi im working on a round based Zombie shooter and it works fine. But if i want to open it in the webplayer nothing happens the only problem the Console shows is: IndexOutOfRangeException: Array index is out of range.
This is my Code:
var enemyPrefabs : Transform[]=new Transform[1]; var amountEnemies = 0; static var multiplicator=5; var lvl=1; var spawnPoints : Transform[]=new Transform[12];
function Update(){
multiplicator=Time.time*0.005+3; if(GameObject.Find("Enemy(Clone)")==false&&Time.time>5){ lvl+=1; amountEnemies+=5; Invoke("Up",0);
} else{ CancelInvoke();
}
} function Up() {
for (i=0; i < amountEnemies; i++) // How many enemies to instantiate total. { var obj : Transform=enemyPrefabs[Random.Range(0,enemyPrefabs.length-1)];// Randomize the different enemies to instantiate. var pos: Transform =spawnPoints[ Random.Range(0,spawnPoints.Length)]; // Randomize the spawnPoints to instantiate enemy at next. Instantiate(obj,pos.position,pos.rotation);
} } I have really no idea how the array could be out of range plss help me.
Please format your code so it's readable.
I'd love to help.
Answer by jahroy · Dec 23, 2011 at 11:20 PM
It's very hard to read your code, but it looks like it has the potential to access a bad index in the spawnPoints array.
You properly limit the max index of your enemyPrefabs array to its length minus one, but you do not exercise the same wisdom when randomizing the index for the spawnPoints array.
Here is your code formatted and fixed:
var spawnPoints : Transform [] = new Transform [12]; var enemyPrefabs : Transform [] = new Transform [1];
var amountEnemies : int = 0; var levelNumber : int = 1;
static var multiplicator : int = 5;
function Update () { multiplicator = Time.time * 0.005 + 3;
var theEnemy = GameObject.Find("Enemy(Clone)");
if ( ! theEnemy && Time.time > 5 ) {
levelNumber ++;
amountEnemies += 5;
Invoke("Up", 0);
}
else {
CancelInvoke();
}
}
function Up () { for ( i = 0; i < amountEnemies; i ++ ) {
var enemyIndex = Random.Range(0, enemyPrefabs.length - 1);
var spawnIndex = Random.Range(0, spawnPoints.length - 1);
var obj : Transform = enemyPrefabs[ enemyIndex ];
var pos : Transform = spawnPoints [ spawnIndex ];
Instantiate(obj,pos.position,pos.rotation);
}
}
Your answer
![](https://koobas.hobune.stream/wayback/20220613062333im_/https://answers.unity.com/themes/thub/images/avi.jpg)