- Home /
Trouble instantiating an Array of Prefabs
I've been trying to create an array of prefabs based on some answers I found here, but I'm not having any luck. I keep getting a null reference error. I'm sure this is a simple problem, but I'm a noob and can't solve it. Any help would be greatly appreciated.
Here's the code i have so far:
public GameObject[][] tiles_array;
public GameObject tilePrefab1;
public int boardWidth = 32;
public int boardHeight = 32;
float tileWidth = 5.0f;
float tileHeight = 5.0f;
void Start () {
Debug.Log("fart");
tilePrefab1 = Resources.Load("tilePrefab1", typeof(GameObject)) as GameObject ;
for (int i = 0; i < boardWidth; i++)
{
tiles_array[i] = new GameObject[boardWidth];
for (int j = 0; j <boardHeight; j++)
{
tiles_array[i][j]= (GameObject)Instantiate(tilePrefab1, new Vector3(i*tileWidth,j*tileHeight,-2), Quaternion.identity);
}
}
}
Answer by Eric5h5 · Oct 15, 2014 at 08:11 PM
You didn't initialize the array. Also, it would be simpler to use a 2D array instead of a jagged array...easier to initialize since you can just initialize the 2D array instead of having to initialize all of the arrays in the jagged array individually.
Thank you! I switched to a 2D array and now it's at least loading. But now I have a quick follow-up, I want to create "off-set" tiles like this , but I currently have this with a 2D array. I can get the desired effect using a second array offset by 1/2 the tile height/width, BUT in the future if I want to change tiles based on position (suppose a character is on top of them) I can see that making things confusing. Would a jagged array be easier for that?
Here's the current code BTW:
void Start () {
tiles_array = new GameObject[boardWidth,boardHeight];
tilePrefab1 = Resources.Load("tilePrefab1", typeof(GameObject)) as GameObject ;
for (int i = 0; i < boardWidth/2; i++) {
for (int j = 0; j
}
}
for (int k = 0; k < boardWidth/2; k++) {
for (int l = 0; l
}
}
}