What Node Type to use? GraphNode, GridNodeBase, GridNode, LevelGridNode

Currenty I use this function to get the nearest walkable node near to my mouse cursor

        public static GraphNode GetNearestWalkableNode(Vector3 position)
        {
            var constraint = NNConstraint.None;
            constraint.constrainWalkability = true;
            constraint.walkable = true;

            return AstarPath.active.GetNearest(position, constraint).node;
        }

This returns GraphNode. But I use a LayerGrid and there is also GridNode (for GridGraph) and LevelGridNode (for LayerGraph). How can I use them? It’s not possible to just cast them as LevelGridNode and I’ve found no method in the LayerGrid that returns me a LevelGridNode in any way.

Only thing I’ve found was

        AstarPath.active.graphs[0].GetNodes(node => {
                Debug.Log(node.GetType());
        });

These are all LevelGridNodes

Hi

When using a Layered grid graph, the node type will be LevelGridNode. When using a regular grid graph, the node type will be GridNode. Both of those type inherit from GridNodeBase, which in turn inherits from GraphNode.

1 Like

Thanks for the reply. This is what I could see also see in the code. For me, it was a little bit confusing, because

AstarPath.active.graphs[0].GetNearest(position, constraint).node;

returns a GraphNode

image

but it’s actually a LevelGridNode:

Debug.Log(AstarPath.active.graphs[0].GetNearest(position, constraint).node.GetType()); // LevelGridNode

So, I was a little bit confused. This is now my final approach; seems to work:

        public static LevelGridNode GetNearestWalkableNode(Vector3 position)
        {
            var constraint = NNConstraint.None;
            constraint.constrainWalkability = true;
            constraint.walkable = true;

            return (LevelGridNode)AstarPath.active.graphs[0].GetNearest(position, constraint).node;
        }

GetNearest works for all graph types, so it has to return their common base class. If you want to do different things for different graphs, or if you know you only have one graph, then you can cast it if you need to.

1 Like