My code is:
player = get_tree().get_current_scene().get_node("Objects/Player")
It's not returning any errors but seems like it isn't working. Can anyone help?
My code is:
player = get_tree().get_current_scene().get_node("Objects/Player")
It's not returning any errors but seems like it isn't working. Can anyone help?
Maybe try printing the scene tree with print_tree_prity
(documentation) and see if the node exists at that path?
Try this:
func print_nodes():
# Prints all nodes for current scene
var parent_node=get_node("..")
var child_nodes = get_children()
print("List of child nodes:")
for i in child_nodes:
print( i.get_name())
If the list returns the node "Sprite", then this code:
var node = get_node("Sprite")
... should be valid.
I am currently writing a project where I am using a structure:
root --> Main --> (character, currentLoadedScene, npc1, npc2, npc3, ... , monster1, monster2, ..., item1, item2, ..., dialogue_box)
-- More depth exists to the tree than what is described above; but it is siloed to the given scene. The only levels that contain information which matters is depth 1 ("Main") and depth 2 ("Children_of_Main"). If 'npc1' really needs data from 'monster1' (because I got ambitious and wanted npcs to attack monsters, or something equally crazy), then all it needs to do is pass the request to the Main node, which has utilities to grab information from any of it's children nodes. I don't know if this is the best practice for godot, but it seems to make sense in my head.
-- -- By the way... if anyone thinks that they have a "more intelligent" design structure, or even just a design structure that they like for node hierarchy composition; please describe it to me! I am all ears, I would love to have another design pattern in my toolkit to play with!
To debug issues with "get_node(<node_name>)"; I have been using code like what you see above to solve the problem of determining which nodes can be accessed.
I have this function as a utility function in "Main":
func safe_get_node(node):
var parent_node=get_node("..")
var child_nodes = get_children()
var node_exists = false
for i in child_nodes:
if(node == i.get_name()):
node_exists = true
if(node_exists):
return get_node(node)
else:
return null
I admit that this mechanism for "safely" grabbing nodes is expensive... but it's the only way I've found that I can attempt to grab a node without the risk of the code emitting a "Node not found error"; and the mechanism is outstanding for debugging purposes.
Thanks very much!
No problem. Good luck!
Doesn't find_node()
also work if you don't know the node's exact path? There's also get_node_or_null()
if you want to get a node that may not exist. This won't display an error message if the node doesn't exist.
I wasn't previously aware of "find_node()" or "get_node_or_null()". It sounds like there's a good chance that those would be faster than the mechanism that I previously recommended.