Array index out of range(C#)
Hey :) I have seen this problem in many other cases, but I haven't been able to use those fixes on my problem. I get IndexOutOfRangeExeption: Array index is out of range and it points to line 44. The
Instantiate(challanges [Random.Range(0, challanges.Length)], challengesSpawnPoint.position, Quaternion.identity);
public float scrollSpeed = 5.0f;
public GameObject[] challanges;
public float frequency = 0.5f;
float counter = 0.0f;
public Transform challengesSpawnPoint;
// Use this for initialization
void Start () {
GenerateRandomChallange ();
}
// Update is called once per frame
void Update () {
//GenerateObjects
if (counter <= 0.0f) {
GenerateRandomChallange ();
} else {
counter -= Time.deltaTime * frequency;
}
//Scrooling
GameObject currentChild;
for (int i = 0; i < transform.childCount; i++) {
currentChild = transform.GetChild (i).gameObject;
ScrollChallange(currentChild);
if (currentChild.transform.position.x <= -15.0f) {
Destroy (currentChild);
}
}
}
void ScrollChallange (GameObject currentChallange){
currentChallange.transform.position -= Vector3.right * (scrollSpeed * Time.deltaTime);
}
void GenerateRandomChallange(){
Instantiate(challanges [Random.Range(0, challanges.Length)], challengesSpawnPoint.position, Quaternion.identity);
counter = 1.0f;
}
} I'm watching a tutorial where he changes the size from 0 to 1 and Gameobjects into the "challenges", but when i try to change it from 0 to 1. It just changes itself back to 0. Does anybody know how to fix this? Thanks in advance!
Instantiate(challanges [Random.Range(0, challanges.Length)], challengesSpawnPoint.position, Quaternion.identity);
This code fails when the challanges array is empty. Did you put at least one object into it in the inspector?
BTW: Even if you think the array can never be empty, it's good practice to check the array size for 0 before trying to access any element.
Answer by Max_Bol · Dec 15, 2016 at 03:39 AM
To complete doublemax with a simple correction, try this :
if(challanges.Length > 0){
Instantiate(challanges [Random.Range(0, challanges.Length -1)], challengesSpawnPoint.position, Quaternion.identity);
}
Remember that Array.Length returns the total amount in the array. So, if you got 4 challanges (funny typo error there btw) in the array, Random.Range(0, challanges.Length) will return a number between 0 and 4 while you're actually looking for a random number between 0 (1st challanges) and 3 (4th challange)
Arrays' ID always starts at 0 with its first "member" while while Array.Length and List.Count return the total members.