Setting a property in a 2D array giving me an Object not set to Instance error.

I’ve created a class called Cell which has one property which is an int called Value. I’m trying to create a 2D array to create a grid of cells with random values, however whenever I try to set the value of Cell [x, y] I get this error;

NullReferenceException: Object
reference not set to an instance of an
object

I know this means that the object isn’t getting created correctly, but I can’t see why.

My Cell class
public class Cell : iCell {

	int _value;

	public int Value {
		get {return _value;}
		set {_value = value; }
}
	public Cell ()
		{
			_value = 0;
		}
}

My Grid Class

public class SudokuGrid : iSudokuGrid {

		private Cell[,] _cells;
		private Cell _currentCell;
		private Cell _previousCell;


		public Cell[,] Cells {
			get { return _cells; }
			set { _cells = value; }
		}	
		public Cell CurrentCell {
			get { return _currentCell;}
			set { _currentCell = value;}
		}
		public Cell PreviousCell {
			get { return _previousCell;}
			set { _previousCell = value;}
		}

		public SudokuGrid() {

			Cell [,] _cells = new Cell[9,9];
			//int x = 0;
			//int y = 0;
		}

		public void Generate() {

			for (int x = 0; x < 9; x++) {
				for (int y = 0; y < 9; y++) {
					int rnd = Random.Range(1,9);
					_cells[x, y].Value = rnd;
					UnityEngine.Debug.Log(x.ToString() + " " + y.ToString());

				}
			}	
			UnityEngine.Debug.Log("Process finsihed ");
		}
}

The error is coming from line 38

_cells[x, y].Value = rnd;

I’ve created a script called Debug and I generate the Grid object in start(), not I’ve switched up the code a bit while trying to figure out what was going wrong…

void Start () {
		SudokuGrid grid = new SudokuGrid ();	
		//grid.Generate ();
		grid.Cells [2, 3].Value = 5;
		UnityEngine.Debug.Log (grid.Cells [2, 3].Value.ToString ());
}

Hi, you instantiate an array of Cells. This is correct but the elements of the array are Cell reference or pointer, but they are each empty = null after the array is instantiated.

You need to instantiate a new Cell() for each element of the array!

If it was a value type like an int or a struct you wouldn’t need to do that, but as it is a class, they need to be instantiated one by one.