How to get all child of nodes in c#?

Godot Version

4.1.1 mono

Question


I don’t want use: node.GetChild(0).GetChild(0).GetChild(0).GetChild(0).GetChild(0).Name
This form of code is not professional.
Thanks.

Do you want all children AND all grand children?
If so, I would advise you to use a recursive method, checking all children nodes from your starting node.

I can’t test what I write right now, but this is how I see it:

private bool checkTargetExist(Node node, string targetName)
{
    foreach(Node child in node.GetChildren())
    {
        if(child.Name == targetName || checkTargetExist(child, targetName))
        {
            return true;
        }
    }

    return false;
}

If a node does not have any child, it will be skipped.

Hope this helps !

1 Like

Thank you, Finally I fixed with FindChild() function:

if(GetTree().Root.GetChild(0).FindChild("targetCollisionX*") != null){ return false; } return true;

Alright, but this will work only if your target node is a child of the first child of your root.
You can use the FindChild() method in the example I posted above, so you can always reuse the method for another target node !

And I think you swapped your if statement returns.
Shouldn’t it be :

if(... != null)
{ 
 return true;
}
return false;

?
Which you can replace by this clean one liner:

return GetTree().Root.GetChild(0).FindChild("targetCollisionX*") != null;
1 Like

You are a good programmer. Thanks a lot :gdhearteyes:

1 Like

This topic was automatically closed 30 days after the last reply. New replies are no longer allowed.