Array Out Of Range C#
I am new to unity and my code below gives me the error; Array index is out of range. Could someone explain to me why this happens and the possible solutions. Thanks! I could post any other things necessary.
Inspector:
Error:
Code:
using UnityEngine;
using System.Collections;
public class SpawnPrefab : MonoBehaviour {
public GameObject[] enemies;
public int amount;
private Vector3 spawnPoint;
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
enemies = GameObject.FindGameObjectsWithTag ("Apple");
amount = enemies.Length;
if (amount != 3) {
InvokeRepeating ("spawnEnemy", 5, 10f);
}
}
void spawnEnemy() {
spawnPoint.x = Random.Range (9, 6);
spawnPoint.y = Random.Range (9, 6);
Instantiate(enemies [UnityEngine.Random.Range(0, enemies.Length - 1)], spawnPoint, Quaternion.identity);
CancelInvoke ();
}
}
Could you edit your post and place a comment in the code to let us know where the error is? Something like this
//<---- error here
You are using GameObject.FindGameObjectsByTag()
in Update()
without any throttling, which is not so great for performance—Unity has to search through every object...every frame!
If you know which items should be in that array, it would be better to manually assign them in the editor by dragging the desired game objects to that component—or do it once in the Start()
method.
If you don’t know which items should be in the array, and/or they do need to be assigned at runtime, you should look into some strategies for limiting how often Unity has to search.
Answer by TBruce · Jun 10, 2016 at 02:32 AM
Try this
if (enemies.Length > 0)
{
if (enemies.Length == 1)
{
Instantiate(enemies [0], spawnPoint, Quaternion.identity);
}
else
{
// since 0 and enemies.Length are int values then enemies.Length is exclusive meaning you will get a result between 0 and (enemies.Length - 1)
int index = UnityEngine.Random.Range(0, enemies.Length);
Instantiate(enemies [index], spawnPoint, Quaternion.identity);
}
}
Take note!
Random.Range
with type float
has both inclusive lower and upper bounds.
Random.Range
with type int
has an inclusive lower bound, but exclusive upper bound.
So @$$anonymous$$avina is correct that Random.Range(0, enemies.Length)
will provide the correct range.
Answer by btmedia14 · Jun 10, 2016 at 01:14 PM
I noticed the following in your code sample. At line 20 :
if (amount != 3) {
InvokeRepeating ("spawnEnemy", 5, 10f);
This implies spawnEnemy() is called even when amount is zero, i.e. when there are no enemies. When enemies[] array is referenced the index is undefined. Perhaps determine if this is the condition required, maybe amount >= 3 for example.
Your answer
![](https://koobas.hobune.stream/wayback/20220612082621im_/https://answers.unity.com/themes/thub/images/avi.jpg)