Hi this is my first post here, I am new to coding.
I am making a tile-based tower defense game and using BFS to create enemy pathfinding. I get a NRE at runtime and it highlights the enemy object pool gameobject the script is attatched to.
public class Pathfinder : MonoBehaviour
{
[SerializeField] Vector2Int startCoordinates, endCoordinates;
Vector2Int[] directions = {Vector2Int.right, Vector2Int.left, Vector2Int.up, Vector2Int.down};
Node startNode, endNode;
[SerializeField] Node currentSearchNode;
GridController gridController;
Dictionary<Vector2Int, Node> gridDictionary, reachedDictionary;
Queue<Node> frontier = new Queue<Node>();
void Start()
{
gridController = FindAnyObjectByType<GridController>();
if (gridController != null )
{
gridDictionary = gridController.GridDictionary;
}
startNode = new Node(startCoordinates, true);
endNode = new Node(endCoordinates, true);
BreadthFirstSearch();
}
void BreadthFirstSearch()
{
bool isRunning = true;
frontier.Enqueue(startNode);
reachedDictionary.Add(startCoordinates, startNode); // This line is throwing the error
while (frontier.Count > 0 && isRunning)
{
currentSearchNode = frontier.Dequeue();
currentSearchNode.bIsExplored = true;
ExploreNeighbors();
if (currentSearchNode.vCoordinates == endCoordinates)
{
isRunning = false;
}
}
}
void ExploreNeighbors()
{
List<Node> neighbors = new List<Node>();
foreach (Vector2Int direction in directions)
{
Vector2Int neighborCoordinates = currentSearchNode.vCoordinates + direction;
if (gridDictionary.ContainsKey(neighborCoordinates))
{
neighbors.Add(gridDictionary[neighborCoordinates]);
}
}
foreach (Node neighbor in neighbors)
{
if (!reachedDictionary.ContainsKey(neighbor.vCoordinates) && neighbor.bIsTraversable)
{
reachedDictionary.Add(neighbor.vCoordinates, neighbor);
frontier.Enqueue(neighbor);
}
}
}
}
Sorry if this is messy, so is my project lol