RemoveChild and AddChild freeze the game, need to use CallDeferred, why?

Godot Version

4.2.1

Question

Hi, When I’m removing child from parent and setting a new parent my game freeze

public partial class InventoryComponent : Node2D
{
	public void AddItem(Item item) {
		item.GetParent().RemoveChild(item);
		AddChild(item); // Freeze here, CPU thread usage goes 100%
	}
}

I google it and find out that I need to use CallDeferred method
Why is that? I don’t really understand

In docs there is an example of using AddChild without calling CallDeferred:

Node childNode = GetChild(0);
if (childNode.GetParent() != null)
{
    childNode.GetParent().RemoveChild(childNode);
}
AddChild(childNode);

but it does’t work for me, I need to call CallDeferred for AddChild

Okey nevermind, I found topic about it

2 Likes

but someone should update the docs: Node — Godot Engine (stable) documentation in English

add_child(child_node)

with

call_deferred("add_child", child_node)
1 Like