- Home /
NullReferenceException when working with multidimensional array
Hi. I've searched high and low, but the below script is still giving me problems:
public Transform[,] tileReferences; public Transform tilePrefab;
void Start() { map = new Tile[(int)levelSize.x, (int)levelSize.y];
for(int x = 0;x<levelSize.x;x++) {
for(int y = 0;y<levelSize.y;y++) {
Transform instantiatedTile = (Transform)Instantiate(tilePrefab, new Vector3(x,0,y), transform.rotation);
instantiatedTile.gameObject.name = x + " " + y;
//tileReferences[x, y] = instantiatedTile;
}
}
}
The commented out line is giving me the error: NullReferenceException: A null value was found where an object instance was required.
What is the null value? As you can see, instantiatedTile
isn't null because I can access it's name no problem. It must be something with the way I'm accessing the array, right?
Could somebody kindly explain why this is happening? I'm not very familiar with multidimensional arrays.
Answer by DaveA · Apr 06, 2011 at 07:44 PM
You have not allocated the array. Try putting this as the first line of Start:
tileReferences = new Transform[levelSize.x,levelSize.y];
Well silly me. Glad I found this answer after wasting about an hour! Eventually I'll learn C#'s very-different-from-python ways ;) thanks!
Your answer
