No, sadly that still only returns the first child. I’ve heard using get_next() works, but I can’t ever get it to work.
DigitalDrako | 2020-06-13 20:54
What’s the output of this: print(get_child_count ())
deaton64 | 2020-06-13 21:08
To me this returns all the children of the node in the stable version of godot:
for _i in self.get_children ():
print (_i)
o is referred to grandchildren, etc?
estebanmolca | 2020-06-13 21:10
it prints 1. The children I’m trying to get are all instances of the same scene. Could this be why it’s only returning 1?
DigitalDrako | 2020-06-13 21:10
sounds like it. Add this print(get_parent()) to _ready() It will tell you the parent.
It depends what you want to do, but you could add all of the instances to a a group, such as: add_to_group("nmeships")
Which is what I do for all of my enemy ships. Then to get all of my enemy ships, I do: var _nmeships = get_tree().get_nodes_in_group("nmeships")
And to loop through them: for _enenmy in _nmeships:
deaton64 | 2020-06-13 21:22
Thats super smart, thanks! I haven’t been using groups in this project, so it’s nice to know when they can be used
DigitalDrako | 2020-06-13 21:24
you’re welcome, I can’t remember where I picked that up from, could have been a Udemy course.
deaton64 | 2020-06-13 21:26
From the Doc:
TreeItem get_children ( )
Returns the TreeItem’s first child item or a null object if there is none.
and
TreeItem get_next ( )
Returns the next TreeItem in the tree or a null object if there is none.
I thought of using
get_children and get_next loop to fetch one by one.
But it seem get_children returns all the children of the node as an array.
I don’t know if there is a built in way to do this. But you can use this…
func get_all_children(in_node,arr:=[]):
arr.push_back(in_node)
for child in in_node.get_children():
arr = get_all_children(child,arr)
return arr
and call it like…
var all_children = get_all_children(the_node)
“the_node” being the node of which you want to get children of. The returned array will have self included as the first node.
You can make it a static function and put it in a class or singleton so you can call it from anywhere in the project.
This question is two years old and I’ve long solved this problem, but I appreciate your dedication
DigitalDrako | 2022-07-10 18:35
I take that back! I just found this thread again (after googling the same question), and your answer? Fantastic.
Another way to iterate all of the children that isn’t recursive and doesn’t require collecting all nodes before processing is to iterate with a list of nodes that you haven’t processed:
var waiting := get_children()
while not waiting.empty():
var node := waiting.pop_back() as Node
waiting.append_array(node.get_children())
print(node) # do something with the node here
Here, I don’t care about the order of the nodes so I use pop_back because it’s more efficient. It traverses the nodes with by always processing a parent before its children.