Null Reference Exception when trying to reach an element of an array

First I made an array in my MapGrid class.
protected TGridArray[,] gridArray;

I have another class called PathNode

public class PathNode
    {
        public Vector2Int coordinate;
        public int gCost, hCost, fCost;
        public PathNode parent;
        public int weightFactor;

        public PathNode()
        {

        }
    }

And I have a subclass which is inherit the MapGrid class as well as the gridArray variable array.

public class NavigationGrid : MapGrid<PathNode>
    {
        //Constructor
        public NavigationGrid(int width, int height, float cellSize, Vector3 startingPosition = default)
        {
            this.width = width;
            this.height = height;
            this.cellSize = cellSize;
            this.startingPosition = startingPosition;

            gridArray = new PathNode[width, height];
            for (int x = 0; x < gridArray.GetLength(0); x++)
                for (int y = 0; y < gridArray.GetLength(1); y++)
                    gridArray[x, y].coordinate = new Vector2Int(x, y);
        }

And when I want to make a NavigationGrid in my monobehaviour script I get an error because of this piece of the constructor:
gridArray[x, y].coordinate = new Vector2Int(x, y);

I want to use in the monobehaviour script like this:

grid = new NavigationGrid(width, height, cellSize, originalPosition);

The error message says this:

NullReferenceException: Object reference not set to an instance of an object
Bober.UnityTools.NavigationGrid…ctor (System.Int32 width, System.Int32 height, System.Single cellSize, UnityEngine.Vector3 startingPosition) (at Assets/Scripts/MapGrid.cs:202)
Testing.Start () (at Assets/Scripts/Testing.cs:34)

I made some debug and the
gridArray = new PathNode[width, height];
line doing its job well and give the correct size to the array but after that i cannot write to the [0, 0] element of the array.
What is the problem with it?

You are creating your array fine but it’s an array of nulls. So, on that line (line 14 in the post, presumably line 202 in the actual file), you are trying to set the field “coordinate” of a null object. You need a line like this there first:

gridArray[x, y] = new PathNode();

Some notes on how to fix a NullReferenceException error in Unity3D

  • also known as: Unassigned Reference Exception
  • also known as: Missing Reference Exception

http://plbm.com/?p=221

The basic steps outlined above are:

  • Identify what is null
  • Identify why it is null
  • Fix that.

Expect to see this error a LOT. It’s easily the most common thing to do when working. Learn how to fix it rapidly. It’s easy. See the above link for more tips.