I've been trying to figure it out on my own, but I can't find the problem

I’ve reached the 27 minute mark of this video after going through it twice and making sure I’ve done everything correctly, yet its still not working, I keep getting the error ‘NullReferenceException: Object reference not set to an instance of an object’

But I am almost certain my testing script is exactly the same as the video which is where the error takes me.

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Testing : MonoBehaviour
{

    [SerializeField] private Unit unit;
    


    private void Start()
    {
       

      
    }

    private void Update()
    {
        if (Input.GetKeyDown(KeyCode.T))
        {
            GridPosition mouseGridPosition = LevelGrid.Instance.GetGridPosition(MouseWorld.GetPosition());
            GridPosition startGridPosition = new GridPosition(0, 0);

            List<GridPosition> gridPositionList = Pathfinding.Instance.FindPath(startGridPosition, mouseGridPosition);

            for (int i = 0; i < gridPositionList.Count - 1; i++)
            {
                Debug.DrawLine(
                    LevelGrid.Instance.GetWorldPosition(gridPositionList[i]),
                    LevelGrid.Instance.GetWorldPosition(gridPositionList[i + 1]),
                    Color.white,
                    10f
                );
            }
        }
    }


}

Can you show the error you get in the console. It will give a good indication of where to look for the culprit

There are three thigns that can yield a null result in the Update method:

LevelGrid.Instance
Pathfinding.Instance
gridPositionList.

It’s extremely unlikely that LevelGrid.Instance is null or you wouldn’t have gotten quite this far in the course.

That leaves Pathfinding.Instance or gridPositionList.

Double click on your error, if it brings you to the line that reads

List<GridPosition> gridPositionList = Pathfinding.Instance.FindPath()

Then the Pathfinding Instance has not been properly set.
If the error is on

for (int i=0; i<gridPositionList.Count -1; i++)

Then the FindPath() method is returning null instead of a list.

In either case, if this doesn’t lead to the issue, Let us know which of the two lines the error was on, and paste in the extended error message as well as your Pathfinding.cs code.

Privacy & Terms