As you can see here, for some reason when I tried having the starting waypoint be 0,0 and the end waypoint be 2,0 the program froze before it could start the game proper. The log you can see in the screenshot is from the previous attempt where the start waypoint was 0,0 and the end waypoint was 1,0. Why is it freezing?
Here is the code from Pathfinder if it helps:
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Pathfinder : MonoBehaviour
{
[SerializeField] Waypoint startWaypoint, endWaypoint;
Dictionary<Vector2Int, Waypoint> grid = new Dictionary<Vector2Int, Waypoint>();
Queue<Waypoint> queue = new Queue<Waypoint>();
[SerializeField] bool isRunning;
Vector2Int[] directions = { Vector2Int.up, Vector2Int.right, Vector2Int.down, Vector2Int.left };
// Start is called before the first frame update
void Start()
{
LoadBlocks();
ColorStartAndEnd();
Pathfind();
}
private void Pathfind()
{
queue.Enqueue(startWaypoint);
while (queue.Count > 0 && isRunning)
{
var searchCenter = queue.Dequeue();
print("Searching from: " + searchCenter); // todo remove log
HaltIfEndFound(searchCenter);
ExploreNeighbors(searchCenter);
searchCenter.isExplored = true;
print("still in Pathfind while loop");
}
print("Finished pathfinding?");
}
private void HaltIfEndFound(Waypoint searchCenter)
{
if (searchCenter == endWaypoint)
{
print("Searching from end node, therefore stopping"); // todo remove log
isRunning = false;
}
}
private void ExploreNeighbors(Waypoint from)
{
if (!isRunning) { return; }
foreach (Vector2Int direction in directions)
{
Vector2Int neighborCorrdinates = startWaypoint.GetGridPos() + direction;
try
{
Waypoint neighbor = grid[neighborCorrdinates];
neighbor.SetTopColor(Color.blue);
queue.Enqueue(neighbor);
print("Queueing " + neighbor);
}
catch
{
//KeyNotFoundException
}
}
}
private void ColorStartAndEnd()
{
startWaypoint.SetTopColor(Color.green);
endWaypoint.SetTopColor(Color.red);
}
private void LoadBlocks()
{
var waypoints = FindObjectsOfType<Waypoint>();
foreach (Waypoint waypoint in waypoints)
{
bool isOverlapping = grid.ContainsKey(waypoint.GetGridPos());
if (isOverlapping)
{
Debug.LogWarning("Skipping overlapping block: " + waypoint);
}
else
{
grid.Add(waypoint.GetGridPos(), waypoint);
}
}
print("Loaded " + grid.Count + " blocks");
}
}