Godot can't add child already has parent

I’m making a tower defense game in godot, and when I spawnthe same node I get the error:

E 0:00:03:0336   spawner.gd:20 @ _on_timer_timeout(): Can't add child 'NormalEnemy' to 'PathFollow2D', already has a parent 'PathFollow2D'.
  <C++ Error>    Condition "p_child->data.parent" is true.
  <C++ Source>   scene/main/node.cpp:1411 @ add_child()
  <Stack Trace>  spawner.gd:20 @ _on_timer_timeout()

now to fix this error I moved it to a loop, but when it’s in the loop that node starts moving on the track faster and faster and nothing else spawns, and there are zero errors. Here is the code that doesn’t give an error:

extends Node2D
@onready var basic_zombie = preload("res://scenes/Normalenemy.tscn")
@onready var timer = $Timer
@onready var spawnpoint = %PathFollow2D

#var canspawn = true

#func _process(delta):
	#var basicenemy = basic_zombie.instantiate()

func _on_timer_timeout():
	var basicenemy = basic_zombie.instantiate()

What starts the timer?

Regarding the error, have you tried to use Node.reparent instead of add_child, since the latter requres, that the added node has no parent.

1 Like

In other words, I think that when you add an enemy, you are not creating a new instance of the enemy, but trying to add the existing enemy again. I work in c#, so I don’t really remember how to get around this in Godot, but looking at the code, I’m not sure if this is the case. If the error arises from my theory, then when you preload an enemy, you already have an instance of the enemy created instead of a prefab. In that case, you could try for the sake of the test to load the enemy every time the time loop expires, but that would affect performance.

it’s autostart

I’ll try this, but I can’t figure out how I would use this

Just call basicenemy.reparent(spawnpoint)

I know but I Don’t know how I could apply this to my code

Literally write that to your code above, what’s different about your code?

reparenting it doesn’t work

func _on_timer_timeout():
	var basicenemy = basic_zombie.instantiate()

the same errors happen

You replace the add_child code, like was said above

I tried that to. But nothing spawns.

Then you’re doing something else wrong, you need to explain more what you’re doing to cause it to break, if you just do what your code is above either add_child or reparent will work

well it doesn’t the enemy’s spawned just speed up and speed up

that doesn’t make sense, because if nothing is adding it as a child it can’t spawn