-1

Currently i have spawning system that spawns Easy then medium enemies but I'm getting Array out of range error and it's only spawning 4 of the enemies. i want x20 easy (or general number) x20 medium and then random between (easy,medium and hard enemies.)

This is my code

public GameObject[] enemy; 

public Transform[] spawnPoints;         

private float timer = 2;


int index = 0 ;

int wave = 0;

List <GameObject> EnemiesList = new List<GameObject>();

private int enemyCount=20;


void Update()
{
 timer -= Time.deltaTime;

if (timer <= 0 && wave < 6)
{
    timer = 3;

    if (wave != 0 &&  wave % 2 == 0)
    {
        index ++ ;
    }

    EnemySpawner();

    wave++;
}

}

void Spawn ()
 {
    for (int i = 0; i<enemyCount;i++)
    {
       Invoke("EnemySpawner" , i + 2);
    }
 }

 void EnemySpawner ()
 {
    int spawnPointIndex = Random.Range (0, spawnPoints.Length);

GameObject InstanceEnemies= Instantiate ( enemy[index] , spawnPoints[spawnPointIndex].position , spawnPoints[spawnPointIndex].rotation) as GameObject;

EnemiesList.Add(InstanceEnemies);

}

}
John
  • 141
  • 4
  • 12

1 Answers1

0

The exception might come from enemy[index], your code uses an index of 0, 1, 2. Are there 3 GameObjects advised to enemy[]?

or

spawnPoints[spawnPointIndex] might be empty, so that spawnPoints[0] will lead to that exception. Is there at least one transform in spawnPoints[]?

To prevent the exception you could do something like this:

if ( index > 0 && index < enemy.Length && spawnPointIndex > 0 && spawnPointIndex < spawnPoints.Length )
{
    GameObject InstanceEnemies= Instantiate ( enemy[index] , spawnPoints[spawnPointIndex].position , spawnPoints[spawnPointIndex].rotation) as GameObject;

    EnemiesList.Add(InstanceEnemies);
}
Florian
  • 465
  • 5
  • 17
  • No the error is coming from the Index not the spawnPointIndex, And how can i make the spawning endless please? Thanks :) – John Jun 25 '16 at 10:10