+3 votes

I'm trying to get every child of a node, but the method get_children() only returns the first node. How can I get every child of a node?

in Engine by (198 points)

1 Answer

+7 votes
Best answer

Try this:

for _i in self.get_children():
by (1,963 points)
selected by

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.

What's the output of this: print(get_child_count ())

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?

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?

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:

Thats super smart, thanks! I haven't been using groups in this project, so it's nice to know when they can be used

you're welcome, I can't remember where I picked that up from, could have been a Udemy course.

From the Doc:
TreeItem getchildren ( )
Returns the TreeItem's first child item or a null object if there is none.
TreeItem get
next ( )
Returns the next TreeItem in the tree or a null object if there is none.

I thought of using
getchildren and getnext loop to fetch one by one.
But it seem get_children returns all the children of the node as an array.

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.