Mariam Syafiqah Saidi
Mariam Syafiqah Saidi

Reputation: 35

Spawning enemies in Unity 2D

I wanted to make my enemies appear from top using 'spawn' while rotating on itself.

But I received this error:

IndexOutOfRangeException: Array index is out of range. spawnScript.addEnemy () (at Assets/Scripts/spawnScript.cs:21)

Below is my script:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class spawnScript : MonoBehaviour {

public Transform[] spawnPoints;
public GameObject enemy;
public float spawnTime = 5f;
public float spawnDelay = 3f; 

// Use this for initialization
void Start () {
    InvokeRepeating ("addEnemy", spawnDelay, spawnTime);

}

void addEnemy() {
    // Instantiate a random enemy.
    int spawnPointIndex = Random.Range(0, spawnPoints.Length);
    Instantiate (enemy, spawnPoints[spawnPointIndex].position, spawnPoints[spawnPointIndex].rotation);
}

// Update is called once per frame
void Update () {

}
}

Upvotes: 0

Views: 5280

Answers (2)

Programmer
Programmer

Reputation: 125275

Here is the problem: public Transform[] spawnPoints;

The spawnPoints variable is declared as public which means that you want to fill it up through the Editor. You failed to do that and the size is still 0. When the size is 0, Random.Range will do this Random.Range(0,0) and will return 0. When you feed 0 as index to spawnPoints variable, it will throw that error because there is nothing in that spawnPoints. You must set the size.

This is what it looks like now:

enter image description here

This is what it is supposed to look like:

enter image description here

Notice how I dragged transforms to the spawnPoints array slots on my second screenshot. If you don't do that, expect to get NullException error.

If you don't want to get that error without seting the size then check if spawnPoints.Length > 0 before using it.

if (spawnPoints.Length > 0)
{
    int spawnPointIndex = UnityEngine.Random.Range(0, spawnPoints.Length);
    Instantiate(enemy, spawnPoints[spawnPointIndex].position, spawnPoints[spawnPointIndex].rotation);
}

By making the spawnPoints a public it is assumed that you want to set the size from the Editor. You can also set the size from script but make it a private variable first so that you won't run into issues:

void Start()
{
    //Set the size to 3 then fill it up
    spawnPoints = new Transform[3];
    spawnPoints[0] = yourPint1;
    spawnPoints[1] = yourPint2;
    spawnPoints[2] = yourPint3;
}

Upvotes: 2

dlarukov
dlarukov

Reputation: 1

Error here - int spawnPointIndex = Random.Range(0, spawnPoints.Length);

You should write - Random.Range(0, spawnPoints.Length - 1)

Upvotes: 0

Related Questions