How to add_child() or get_child_count() of child nodes

Godot Version

v4.3.stable.official [77dcf97d8]

Question

Having a parent node (GameManager) with a script how do I get it's child's children count?

I have a stucture like this:
->GameManager (GameManager Script)
---->Spawner

How do I get the Spawner child count or add child to it?
My problem isn’t what functions to use to achieve this but how to access this node and call the functions on the child node.
I tried giving it the path $Spawner.add_child(), it didn’t work.
Also giving it a unique name %Spawner.add_child() didn’t work as well.
What’s the best way to do this? Thanks

Hey!

To get a Child you can try using spawner.get_child_count()

To Add one try Node2D.new() (replace Node2D with the node you actually want to add)

Example:

extends Node

func _ready():
    # Reference the Spawner
    var spawner = get_node("Spawner")

    # Add the Child
    var new_child = Node2D.new()  # Replace with your Node
    spawner.add_child(new_child)

    # Get the child count
    var child_count = spawner.get_child_count()
    # Print it
    print("Spawner has", child_count, "children")

Hope This Helps!

1 Like