- Home /
NullReferenceException: Object reference not set to an instance of an object
Hey guys, whenever I try to give 2Darray/matrix value I get this error: NullReferenceException: Object reference not set to an instance of an object
Here is the code:
using UnityEngine;
using System.Collections;
public class genTerrain2 : MonoBehaviour {
public int[][] qGrid;
public int[][] rGrid;
public int range = 1; //Size of map
void Update()
{
if(Input.GetKeyDown(KeyCode.Space))
{
for (int q = -range; q != range+1; q++)
{
for (int r = -range; r != range+1; r++)
{
qGrid[q+range][r+range] = q;
rGrid[q+range][r+range] = r;
}
}
}
}
}
I get an error in "`qGrid[q+range][r+range] = q;`" and "`rGrid[q+range][r+range] = r;`" lines.
Thanks in advance!
You're seeing this exception because the qGrid and rGrid are not getting values when you start the player.
Answer by AndyMartin458 · Jan 15, 2014 at 07:37 PM
The problem is that you are not initializing these arrays. You cannot blindly assign elements to an array that is not initialized with the new keyword.
Perhaps, you are initializing them in the inspector, but you need to make sure that these arrays are initialized. You'll need to initialize them in a way like this. Try looking here for a reference. http://msdn.microsoft.com/en-us/library/aa288453%28v=vs.71%29.aspx
void Start()
{
// Jagged array.
int[][] qGrid = new byte[5][]; //one way
int[][] rGrid = { new int[] {2,4,6}, new int[] {1,3,5,7,9} }; //2nd way
}
Your answer
Follow this Question
Related Questions
Array assignments not behaving as expected. 2 Answers
array initialisation c# 1 Answer
[Solved] Actually totally explainable NRE with 2D array 0 Answers
Procedural construction 1 Answer
Multidimensional GameObject Arrays 1 Answer