Once again: The correct way to check if a node exists?

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By MOSN

Lets say I have a node and it has a child node named “target”.

“If $target” causes problems because a “previously freed instance” passes that check for some reason. Same goes for “if $target != null”.

“if $target is Node2D” seems to work better, but will still on rare occasion give me the error “get_node: Node not found: target”. It doesn’t crash the game so that’s something, and I assume it still returns false like its supposed to, but it seems like it causes a bit of lag.

It’s nothing that ruins the game or anything, but it seems like there should be an error free method to check if a node still exists. And preferable a method that doesn’t only work to test if a node has a child node with a specific name, since I also use this for variables.

:bust_in_silhouette: Reply From: Magso

Two methods down from get_node() in the docs get_node_or_null(), I honestly think that $ should be changed to get_node_or_null() to avoid problems like this.

Ahh thanks. Does seem like that might as well be the default yea.
Btw I don’t suppose this can also be used on variable to check if it’s an existing Node? After all I can’t use get_path() since that causes a crash on null. I guess maybe I can store the Node path instead of the node itself in the variable and use that?

MOSN | 2020-04-21 14:52

Yeah, like get_node_or_null(NodePath variable). I’m sure it’s also possible to store a node as a variable and check it.

if !node_var:
    node_var = get_node_or_null(...)
else:
    #do stuff

Magso | 2020-04-21 15:22

1 Like