Using remove child on a previously added node returns an error

Godot Version

4.2.1 stable


for some context i’m trying to make a very simple system that adds a wand on screen when 1 is pressed and removes it if it’s pressed again
the way i’ve worked with that until now is that i’ve made a wand scene that i remove onready
then if i press 1 and some conditions are met the wand (and thus the node) will be added via add_child in this little bit of code

func get_wand_in_out():
	var wand = wand_scene.instantiate()
	if Input.is_action_pressed("First_wand") and wand_out == false:
		await get_tree().create_timer(0.2).timeout
		wand_out = true

and that works
when i try to remove it with this piece of code

	elif Input.is_action_pressed("First_wand") and wand_out == true:
		await get_tree().create_timer(0.2).timeout
		print("pas ok")
		wand_out = false

it returns the following error :
E 0:00:03:0563 remove_child: Condition “p_child->data.parent != this” is true.

scene/main/node.cpp:1437 @ remove_child()

i don’t really get what doesn’t work since i’m a beginner coding wise and searching the error brought me nowhere…

also if that can help the error does not make the project crash, the only problem is that the wand i’m trying to make disappear doesn’t disappear at all

You could do something like this:

var wand = null # Define wand variable

func get_wand_in_out():
	if Input.is_action_just_pressed("First_wand"):
		await get_tree().create_timer(0.2).timeout # Wait 0.2 seconds
		if is_instance_valid(wand): # If wand is a valid instance (of wand_scene)
			wand.queue_free() # Remove the instance
			wand_out = false # You probably don't need this
		else: # If wand is not an instance of wand_scene
			wand = wand_scene.instantiate() # Make it so
			add_child(wand) # And add it as a child to this node
			wand_out = true # You probably don't need this
1 Like

hey that works a lot better than my code did (and with less lines !)
however i have some new problems

  1. when i press the key it sometimes doesn’t remove the wand, even if i wait a bit
  2. sometimes the wand appears and disappears in just 1 tap
  3. even if that might be just me the appearance and disappearance time seems to be a little inconsistent

still, thanks for the code and putting all of those comment, that way i can really comprehend the code and not just copy paste it

after testing a bit i noticed that both order will be executed at the same time & multiple times but idk if that helps

Use Input.is_action_just_pressed instead of Input.is_action_pressed. The latter tells you whether the button is currently held down, which means it’ll keep returning true until the user lets go of the button. Even a quick button press will often register over several frames.


well now everything works wonderfully, thanks for all the help, both of you !

1 Like

This topic was automatically closed 30 days after the last reply. New replies are no longer allowed.