A* Pathfinding Project

IndexOutOfRangeException when modifying grid


#1

Hello,
I am trying to modify the grid in the 2d example scene using the code from the documentation

AstarPath.AddWorkItem(new AstarWorkItem(() => {
            AstarPath.data.gridGraph.GetNode(x, y).Walkable = true;
            AstarPath.data.gridGraph.CalculateConnectionsForCellAndNeighbours(x, y);
        }));

It works fine with almost all nodes but if one of the x and y coordinate is 0 I get the following error:

IndexOutOfRangeException: Index was outside the bounds of the array.
Pathfinding.GridGraph.CalculateConnections (System.Int32 x, System.Int32 y) (at Assets/Standard Assets/AstarPathfindingProject/Generators/GridGenerator.cs:1466)
Pathfinding.GridGraph.CalculateConnectionsForCellAndNeighbours (System.Int32 x, System.Int32 y) (at Assets/Standard Assets/AstarPathfindingProject/Generators/GridGenerator.cs:1419)

#2

Oops. Yep. That’s a bug.

A fix for this will be included in the next update. In the meantime you can patch your version by replacing the CalculateConnectionsForCellAndNeighbours with this:

/** Calculates the grid connections for a cell as well as its neighbours.
 * This is a useful utility function if you want to modify the walkability of a single node in the graph.
 *
 * \snippet MiscSnippets.cs GridGraph.CalculateConnectionsForCellAndNeighbours
 */
public void CalculateConnectionsForCellAndNeighbours (int x, int z) {
	CalculateConnections(x, z);
	for (int i = 0; i < 8; i++) {
		int nx = x + neighbourXOffsets[i];
		int nz = z + neighbourZOffsets[i];

		// Check if the new position is inside the grid
		// Bitwise AND (&) is measurably faster than &&
		// (not much, but this code is hot)
		if (nx >= 0 & nz >= 0 & nx < width & nz < depth) {
			CalculateConnections(nx, nz);
		}
	}
}

#3

Awesome! thank you Aron!