Trouble with A* Pathfinding Algorithm in Unity: Nodes Not Connecting Properly
I'm working on a personal project and I'm performance testing and I'm currently implementing an A* pathfinding algorithm in Unity for a grid-based game, but I'm working with an scenario with nodes not connecting correctly. When I run the algorithm, it sometimes fails to find a path even when one exists, and I suspect the question lies in how I'm determining walkable nodes. Hereβs a snippet of my code: ```csharp public class Node { public int x, y; public bool walkable; public Node parent; public float gCost, hCost; public float fCost { get { return gCost + hCost; } } } private Node[,] grid; private void CreateGrid(int width, int height) { grid = new Node[width, height]; for (int x = 0; x < width; x++) { for (int y = 0; y < height; y++) { grid[x, y] = new Node { x = x, y = y, walkable = Random.value > 0.2f }; // 20% chance to be unwalkable } } } private List<Node> GetNeighbors(Node node) { List<Node> neighbors = new List<Node>(); for (int x = node.x - 1; x <= node.x + 1; x++) { for (int y = node.y - 1; y <= node.y + 1; y++) { if (x == node.x && y == node.y) continue; // Skip the current node if (x >= 0 && x < grid.GetLength(0) && y >= 0 && y < grid.GetLength(1)) { if (grid[x, y].walkable) { neighbors.Add(grid[x, y]); } } } } return neighbors; } ``` The `GetNeighbors` function is supposed to return all adjacent walkable nodes but sometimes it includes nodes that I expect to be unwalkable. I also get inconsistent results, where the pathfinding algorithm sometimes returns a path, and sometimes it fails with a message that states "No path found" even with a clear route available. To troubleshoot, I added debug logs to check which nodes are being considered as neighbors, and I found that sometimes nodes that should be unwalkable are being treated as walkable. I'm using Unity 2021.3.12f1, and I tried increasing the random threshold for walkability, but the scenario continues. Has anyone encountered a similar question or have insights on how to ensure that only intended walkable nodes are processed? Any suggestions for improvements to my grid or neighbor-checking logic would be greatly appreciated! I'm using C# stable in this project. Am I missing something obvious? My team is using C# for this mobile app. I'm open to any suggestions.