An alternative to the GetNeighbourList function that uses our GridPosition ‘+’ operator override and the gridSystem.IsValidGridPosition function might look like:
private List<PathNode> GetNeighbourList(PathNode node)
{
List<PathNode> neighbourList = new List<PathNode>();
List<GridPosition> neighbourPositionList = new List<GridPosition>()
{
node.GetGridPosition() + new GridPosition( 1, 0), // N
node.GetGridPosition() + new GridPosition( 1, 1), // NE
node.GetGridPosition() + new GridPosition( 0, 1), // E
node.GetGridPosition() + new GridPosition(-1, 1), // SE
node.GetGridPosition() + new GridPosition(-1, 0), // S
node.GetGridPosition() + new GridPosition(-1, -1), // SW
node.GetGridPosition() + new GridPosition( 0, -1), // W
node.GetGridPosition() + new GridPosition( 1, -1), // NW
};
foreach (GridPosition neighbourPosition in neighbourPositionList)
{
if (gridSystem.IsValidGridPosition(neighbourPosition)) {
neighbourList.Add(GetNode(neighbourPosition));
}
}
return neighbourList;
}
Here, we generate all of the grid positions up front, then iterate through them and use the gridSystem to test if they are valid. If the neighbouring position is valid we add the PathNode at that grid position.