Casting GraphNode to GridNode

Hello, I’m using SingleNodeBlocker for my project and lastBlocked property return GraphNode to me. I’m using GridGraph and I want to use GraphNode as GridNode.
Casting like (GridNode)singleNodeBlocker.lastBlocked return me error:

“InvalidCastException: Specified cast is not valid.”

How can I cast GrahpNode to GridNode?

Hi

You have to use the as operator. node as GridNode.

AFAIK ‘as’ operator is only safe version of casting. It returns null when casting is not successful.

In my code, I know lastBlocked property is not null and give me true values. But when I cast it to GridNode, it returns null.

if (currentSingleNodeBlocker.lastBlocked != null)
                {
//Entering here successfully
                    Debug.Log($"Single Node Blocker is not empty");
                    Debug.Log($"Single Node Blocker Position: {currentSingleNodeBlocker.lastBlocked.position}");
                    Debug.Log($"Single Node Blocker Graph Index: {currentSingleNodeBlocker.lastBlocked.GraphIndex}");
                    Debug.Log($"Single Node Blocker Node Index: {currentSingleNodeBlocker.lastBlocked.NodeIndex}");

                    var test = currentSingleNodeBlocker.lastBlocked as GridNode;
                    if (test != null)
                    {
//Not entering here
                    }
                    else
                    {
                        Debug.Log($"Casting is empty");
                    }

                    if ((currentSingleNodeBlocker.lastBlocked as GridNode) != null)
                    {
//Not entering here
                    }
                    else
                    {
                        Debug.Log($"Casting is empty");
                    }
                }
                else
                {
                    Debug.Log($"Last Blocked is empty.");
                }
            }

Are you sure it is a grid node then? Try logging node.GetType().Name

Yes. I’m sure. GetType().Name returning “GridNode”. I double check it again. It’s very strange.

any update about it? I think it’s a kind of bug. Should I investigate more for helping?

Hi

If node.GetType() returns GridNode then a cast to GridNode should not possibly be able to fail. That’s part of the C# language. I would advise you to investigate a bit more.