don't work add_child

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

code:
extends Area2D

onready var player = get_parent().get_node_or_null(“Player”)

var use = false

func _process(delta):
if use == true:
if Input.is_action_just_pressed(“use”):
player.add_child(self)

func _on_wood_body_entered(body):
if “Player” == body.name:
use = true

func _on_wood_body_exited(body):
if “Player” == body.name:
use = false

E 0:00:01.705 add_child: Can’t add child ‘wood’ to ‘Player’, already has a parent ‘Scene’.
<Error C++> Condition “p_child->data.parent” is true.
<Open code C++>scene/main/node.cpp:1282 @ add_child()

:bust_in_silhouette: Reply From: Wakatta

Uhm … the error is pretty self explanatory

Trying to add a node to the scenetree while its already there is a big no no

Possible solutions

#remove then re-add
var node = self
get_parent().remove_child(node)
player.add_child(node)

#create doppelganger
player.add_child(self.duplicate())

Thank you very much, it really works!

BOX_Milk | 2023-02-18 15:26