Small Pathfinding fix for Turn-Based Strategy post-Mulitfloor expansion

Hello everyone,
I had recently finished the Turn-based Strategy course when I came across a small bug when wanting to return to a single floor. As it is currently the Pathfinding script looks for any PathfindingLinks within the scene and if our scene has only 1 floor then it will return an error since the Pathfinding.cs cannot find any PathfindingLink objects. So, I made a simple fix for this, we only need to run a small check if the floorAmount is higher than 1 where needed.

In our SetUp() function


public void SetUp(int width, int height, float cellSize, int floorAmount)
 {
        //Everything above is the same...

        if(floorAmount > 1)
        {
            pathfindingLinkList = new List<PathfindingLink>();

            foreach (Transform pathfindingLinkTransform in pathfindingLinkContainer)
            {
                if(pathfindingLinkTransform.TryGetComponent(out PathfindingLinkMonoBehaviour pathfindingLinkMonoBehaviour))

                {
                    pathfindingLinkList.Add(pathfindingLinkMonoBehaviour.GetPathfindingLink());
                }
            }
        }
    }

Then in the GetPathfindingLinkConnectedGridPositionList() function

private List<GridPosition> GetPathfindingLinkConnectedGridPositionList(GridPosition gridPosition)

    {
        List<GridPosition> gridPositionList = new List<GridPosition>();
        if(floorAmount > 1)
        {
            foreach (PathfindingLink link in pathfindingLinkList)
            {
                if(link.gridPositionA == gridPosition)
                {
                    gridPositionList.Add(link.gridPositionB);
                }
                if(link.gridPositionB == gridPosition)
                {
                    gridPositionList.Add(link.gridPositionA);
                }
            }

            return gridPositionList;
        }
        else
        {
            return null;
        }
    }

Finally in our GetNeighbourList()

private List<PathNode> GetNeighborList(PathNode currentNode)
{
      //Everything above is the same...
       if(floorAmount > 1)
        {
            List<GridPosition> pathfindingLinkGridPositonList = GetPathfindingLinkConnectedGridPositionList(gridPosition);

            foreach (GridPosition pathfindingLinkGridPosition in pathfindingLinkGridPositonList)
            {
                totalNeighborList.Add(GetNode(pathfindingLinkGridPosition.x, pathfindingLinkGridPosition.z, pathfindingLinkGridPosition.floor));
            }  
        }
}

Just wanted to share this small fix in case anyone else ran into this problem in the future.
Hope this helps!

Privacy & Terms