- Home /
Duplicate Question
NullReferenceException with MultiDimensional Array
I am attempting to work with a MultiDimensional array of objects, and have declared it as per c# and unity documentation, but any attempt to access the objects in the array gives a NullReferenceException: Object reference not set to an instance of an object error.
Here is a code sample that shows the problem:
public class map1 : MonoBehaviour
{
mapSquare[,] map = new mapSquare[5,5];
void Start ()
{
Debug.Log (map[0,0].terrainType); //Error is here
}
}
I don't think the problem is with the mapSquare class itself because I used it in a different map system before and it worked fine then. I looked around a little and I saw something about it not allocating the objects in the array correctly so the problem may just be my inexperience in c# syntax. Any help would be appreciated.
Classes like the mapSquare class are 'by reference', so your map array is an array of references to instances of the mapSquare class. You create the array, but you did not initialize each entry of the array to point to an instance of the class. You have a 2D array of null pointers. When you try to use one, you get the error.
Follow this Question
Related Questions
Multiple Cars not working 1 Answer
Distribute terrain in zones 3 Answers
Illuminating a 3D object's edges OnMouseOver (script in c#)? 1 Answer
Flip over an object (smooth transition) 3 Answers