call_deferred() causing _ready() to be called repeatedly

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By keidav

The following code causes an infinite loop calling _ready() over and over again. If I don’t call my function deferred, it works although I get an error suggesting that I call my function deferred. The code is assigning an array of RigidBody2Ds to a node in the object created using get_parent().

func _ready():
    # custom object initialized...

    call_deferred("add_children", object)

func add_children(child_object):
    for i in range(child_object.blocks.size()):
        child_object.blocks_container.add_child(child_object.blocks[i], true)

    child_object.parent.add_child(child_object.blocks_container, true)

The last line is the one causing issues. Assigning a node with children to the parent member.

keidav | 2023-04-05 02:43

Seems a little strange to add another child to the parent from a child node; there’s a different method for that; add_sibling:

If you need the child node to be added below a specific node in the list of children, use add_sibling instead of this method.

Does this work instead? I don’t know what’s in your blocks_container or other nodes to call _ready like this. Perhaps consider an initialize method instead that doesn’t interfere with the tree while it is being built (hence the error regarding call_deferred).

spaceyjase | 2023-04-05 13:45

Thank you for the reply! add_sibling() did nothing, This is my custom object/struct abbreviated for clarity:

object = {
		blocks = [],
		blocks_container = Node2D.new(),
		…
		parent = get_parent(),
		…
	}

keidav | 2023-04-05 14:04

Ended up using an initialize method in place of _ready() to fix the issue.

keidav | 2023-04-06 14:05