- Home /
Array index is out of range (C#) ?
IndexOutOfRangeException: Array index is out of range. Ramdom_Tree.Start () (at Assets/Standard Assets/Scripts/Ramdom_Tree.cs:14)
using UnityEngine; using System.Collections;
public class Ramdom_Tree : MonoBehaviour {
public GameObject[] Cay_Dua = new GameObject[1];
void Start () {
for(var i=0; i< 19; i+=1)
{
transform.position = new Vector3(Random.Range(-200, 200), 0, Random.Range(-200, 200));
Instantiate(Cay_Dua[i], transform.position , transform.rotation); // error
} } }
Answer by Dave-Carlile · Oct 31, 2013 at 05:49 PM
Instead of hard coding the array length in your loop, try this...
for (var i=0; i < Cay_Dua.length; i+=1)
That said, your array apparently doesn't have the number of items in it that you expect.
Answer by ArkaneX · Oct 31, 2013 at 05:34 PM
You're trying to access elements 0 to 18 from Cay_Dua array, but apparently it contains less elements.
Answer by undead-steve · Oct 31, 2013 at 05:38 PM
Cay_Dua is defined as a 1-item array in line 2, so it can't work after the first pass. Also, it's defined but never filled, so you're got an empty 1-unit array - calling instantiate will give you a null ref excecption too.
This array is declared as public, so OP probably filled in in inspector. But it seems less than 19 elements was inserted.
Your answer
Follow this Question
Related Questions
Array index is out of range? 2 Answers
IndexOutOfRangeException 1 Answer
Taking a "Range mapped" value and using it to drive the position of an object. 1 Answer
Strange error with animation: "Time is out of range" 0 Answers
can your Random.Range parameters match with function perameter (javascript) 2 Answers