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*, transform.position , transform.rotation); // error 	*

}

  • }*
    }

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.

You’re trying to access elements 0 to 18 from Cay_Dua array, but apparently it contains less elements.

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.