Null Reference exception when finding path

Please help! I have Null Reference exception - tried to debug, seems like Pathfinding.FindPath does’nt work properly - put in the end
// No path found
Debug.Log(“You shall not pass!”);
return null;
and it shows me it every time i’m trying to draw line with Null Reference exception

all the code is fine as for me, checked it 3or 4 times, searched that nasty bug everywhere… with my luck that bug is somewhere in prefab))

OK, Show us what you have so that we can try to help. Perhaps start with FindPath()

public List FindPath(GridPosition startPosition, GridPosition endPosition)
{
List openList = new();
List closedList = new();

    PathNode startNode = gridSystem.GetGridObject(startPosition);
    PathNode endNode = gridSystem.GetGridObject(endPosition);
    
    openList.Add(startNode);        

    for (int x = 0; x < gridSystem.GetWidth(); x++)
    {
        for (int z = 0; z < gridSystem.GetHeight(); z++)
        {
            GridPosition gridPosition = new GridPosition(x, z);
            PathNode pathNode = gridSystem.GetGridObject(gridPosition);

            pathNode.SetGCost(int.MaxValue);
            pathNode.SetHCost(0);
            pathNode.CalculateFCost();
            pathNode.ResetPreviousPathNode();
        }
    }

    startNode.SetGCost(0);
    startNode.SetHCost(CalculateDistance(startPosition, endPosition));
    startNode.CalculateFCost();

    while (openList.Count > 0)
    {
        PathNode currentNode = GetLowestFCostNode(openList);

        if (currentNode == endNode)
        {
            return CalculatePath(endNode);
        }

        openList.Remove(currentNode);
        closedList.Add(currentNode);

        foreach (PathNode neighbourNode in GetNeighbourList(currentNode))
        {
            if (closedList.Contains(neighbourNode)) continue;
            
            int tentativeGCost = currentNode.GetGCost() + CalculateDistance(currentNode.GetGridPosition(), neighbourNode.GetGridPosition());

            if (tentativeGCost < neighbourNode.GetGCost())
            {
                neighbourNode.SetPreviousNode(currentNode);
                neighbourNode.SetGCost(tentativeGCost);
                neighbourNode.SetHCost(CalculateDistance(neighbourNode.GetGridPosition(), endPosition));
                neighbourNode.CalculateFCost();

                if (!openList.Contains(neighbourNode)) 
                { 
                    openList.Add(neighbourNode); 
                }
            }

        }
    }
    // No path found
    Debug.Log("You shall not pass!");
    return null;
}

holly guacamolly!) found that little buggy)
it was sitting in PathNode -

public void SetHCost(int hCost)
{
    this.**g**Cost = hCost;
}

Thanks, #bixarrio

1 Like

Nice. Good find

This topic was automatically closed 24 hours after the last reply. New replies are no longer allowed.

Privacy & Terms