- Home /
Question by
Tageos · Dec 26, 2015 at 03:11 PM ·
c#for-loopintantiate
Help instantiating from a for loop.
Hey! Im trying to instantiate a 2d-array of gameobjects.
This is what i have:
using UnityEngine;
using System.Collections;
public class WorldGen : MonoBehaviour {
public int height;
public int width;
private GameObject terrainref;
private GameObject[] surfacePoints;
private GameObject[,] blocks;
public GameObject air;
void Start () {
GenerateBlocks ();
surfacePoints = GameObject.Find ("Terrainref").GetComponent<perlin>().surfacePoints;
}
void GenerateBlocks() {
for (int x = 0; x < width; x++){
for(int y = 0; y < height; y++){
blocks[x,y] = Instantiate(air,new Vector3 (x*0.25f,y*0.25f,0),transform.rotation) as GameObject;
}
}
}
}
But all i am getting is "NullReferenceException: A null value was found where an object instance was required" here: blocks[x,y] = Instantiate(air,new Vector3 (x*0.25f,y*0.25f,0),transform.rotation) as GameObject;
I cant find any fault in the code so id appretiate if someone can give me some pointers on how to solve this, thank you!
Comment
Never$$anonymous$$d, i forgot to give the array elements to start with. That was the problem!
Your answer
![](https://koobas.hobune.stream/wayback/20220612053806im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
Multiple Cars not working 1 Answer
Distribute terrain in zones 3 Answers
for/while loops not working, or not updating 1 Answer
Renderer on object disabled after level reload 1 Answer
For-loop and Firebase 0 Answers