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!

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(v=vs.71).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
}