Best Way To Avoid remove_child Error?

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

Removing a child node n:

remove_child(n)

Will add error “Condition ‘idx ==-1’ is true.” to Debugger Errors tab if the referenced node is not a child.

Could guard with:

if is_a_parent_of(n):
    remove_child(n)

What if child was somehow removed in another thread between the guard check and the removal?

:bust_in_silhouette: Reply From: Zylann

The best way to avoid remove_child error is to not remove a child that is not in the tree, or was never added to the tree to begin with. Also, the scene tree is not thread-safe, so there can’t be any thread involved here. If you use threads, avoid modifying the tree from it. Use call_deferred or other synchronization methods to schedule calls on the main thread.

If you don’t use threads, the node is added to the tree and you still get that error, it means two parts of your game want to remove the same child, which means those two parts think they have ownership on that node: either structure your code so that this case can’t happen, or add a check like you proposed.

Quality answer. Thanks. The only part that confused me is when you said that because the scene tree is not thread-safe, “there can’t be any thread involved here”. Is it more accurate to say that multiple threads could be involved here, but should NOT be?

Thread safe APIs — Godot Engine (3.1) documentation in English

goshot | 2019-07-07 18:38