+3 votes

So my issue is that I have a variable called target that is a reference to another node. Right now my camera has a script that looks something like this:

_fixed_process(delta):
    if(target):
        #move to target

This way it moves to any target I set, and if the target is null it ignores it. But I seem to have a problem when I call queue_free() inside of a node that is the target. The error I get is:

Attempt to call function 'get_pos' in base 'previously freed instance' on a null instance.

It seems like target wasn't reset to null after what it was referencing was deleted.

in Engine by (840 points)

2 Answers

+2 votes
Best answer

Maybe you should try checking has_node(target) first, just to make sure the node exists.
If you assign a node to a variable, this assignment is not going to change automatically once you delete the node. Istead, you have to assign null yourself or check if the node exists everytime you want to use it.

by (215 points)
selected by

Thanks, this works for me. Although one small correction this answer needs is that has_node()takes a NodePath as the parameter, not a Node. So this made it a lot more work to replace the simple "is null" check I used earlier because I had to save the NodePath of the target node as well.

Hi, im really new into this and i had the same problem as you! My question is how you get the nodepath from a node? sorry if my question is simple (also sorry for my english, im not a native speaker)

Thanks!

node.get_path() gets you the path from the root. Then you have to get the root and call has_node(path) from there in order to check if the node is still there (aka not deleted). So: get_tree().get_root().has_node(targetPath)

Thanks for answering! this worked :D!

+2 votes

I prefer to work with group.

#to get the target node(s)
get_tree().get_nodes_in_group("target")

#delete target node
remove_from_group("target")
add_to_group("free")

#free all
func delete_free():
    for node2free in get_tree().get_nodes_in_group("free"):
        node2free.free()
by (685 points)

yeah, I considered that option but it might get messy

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 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.