+2 votes

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.

in Engine by (70 points)

1 Answer

+4 votes

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

by (3,233 points)

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?

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(...)
    #do stuff
Welcome to Godot Engine Q&A, where you can ask questions and receive answers from other members of the community.

Please make sure to read Frequently asked questions and How to use this Q&A? before posting your first questions.
Social login is currently unavailable. If you've previously logged in with a Facebook or GitHub account, use the I forgot my password link in the login box to set a password for your account. If you still can't access your account, send an email to webmaster@godotengine.org with your username.