- Home /
 
The question is answered, right answer was accepted
creating prefabs in array
hi, i get an error message stating that the array index is out of range. i need help on where am i making mistake. please explain me wat is the error. i have only one gameobject and i want only that object to be instantiated in loop.
 using UnityEngine;
 using System.Collections;
 
 public class spawner_1 : MonoBehaviour {
     
     //public GameObject card;
     //public GameObject card2;
     
     public GameObject[] prefabPool = new GameObject[1];
     
     // Use this for initialization
     void Start () {        
 
     prefabCreation ();
         //prefabPool = new GameObject[2];
     }
     
     // Update is called once per frame
     void Update () {
         
     }
     
     public void prefabCreation()
     {
         //print ("method start");
 
         for(int i = 0; i < 4; i++)
         {
             //print(i);
 
             for(int j = 0; j < 4; j++)
             {
                 Vector3 position = new Vector3((j * transform.localScale.x) -1.0f, (j * transform.localScale.y) + 1, 0);
                 Instantiate(prefabPool[i],position, Quaternion.identity );
             }
         }
     }
 }
 
              Answer by taxvi · May 29, 2015 at 07:09 AM
on line 9 you create an array of two elements while in the the for loop on line 27 you try to access the first 4 elements of that array
thanks for the response. i tried myself and figured out what is the mistake.
Answer by karma0413 · May 29, 2015 at 09:17 AM
Array index out of range means that you are trying to access a position in the array, that does not exist.
Put in some debug lines that check: 1. How big your array truthfully is 2. Where you are at in terms of accessing it.
 // First, check how big the array truthfully is...
 int a = prefabpool.Length;
 
               You should note that even you have 7 items in your array as an example.... Then the array starts at 0 and ends at 6. Arrays always start at zero
 print (a);
 print (i); // Check which spot in the array you really are trying to use