add_child: I can't add "cube2" gold to "world", I already get a parent "world" error

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

I added code to the home screen that adds an object every 3 seconds, but I’m getting errors.

add_child: Can’t add child ‘cube1’ to ‘world’, already has a parent ‘world’.
add_child: Can’t add child ‘cube2’ to ‘world’, already has a parent ‘world’.
add_child: Can’t add child ‘cube3’ to ‘world’, already has a parent ‘world’.

world.gd

extends Spatial
var obj1 = load("res://cube1.tscn")
var obj2 = load("res://cube2.tscn")
var obj3 = load("res://cube3.tscn")
var ins1 = obj1.instance()
var ins2 = obj2.instance()
var ins3 = obj3.instance()
var rng = RandomNumberGenerator.new()
func f():
	rng.randomize()
	var ran = rng.randi_range(1,3)
	if ran == 1:
		self.add_child(ins1)
	if ran == 2:
		self.add_child(ins2)
	if ran == 3:
		self.add_child(ins3)
	else:
		pass
func _on_tm_timeout():
	f()

the code inside the scenes added to the screen (cube1.gd,cube2.gd,cube3.gd)

extends StaticBody
var v = Vector3(0,1,-50)

func _process(_delta):
	if v.z > 0:
		self.queue_free()
	else:
		v.z += 0.1
		self.set_translation(v)

I’m trying to make an endless simple running game.

:bust_in_silhouette: Reply From: Lopy

You are adding the exact same object repeatedly, what you want to do is add clones of it. That gives you add_child(obj1.instance()).

I didn’t know you could use this like that, thanks. :slight_smile:

SDGN16 | 2021-01-30 22:26

I get the same error but Im using the add_child(instance())

func _ready():

var room = load("res://Assets/corridor_6.tscn")
var roomAmount = 0  
var instance = room.instantiate()
var marker = get_node("Marker3D")

add_child(instance)
instance.translate(Vector3(0, 0, 0,))
roomAmount += 1
print("add")

while roomAmount < 6:
	
	add_child(instance)
	instance.translate(Vector3(6, 1, 0,))
	roomAmount +=1
	print("add")
	print(roomAmount)

Thank you for the answer.

So it’s because the load scene variable isn’t inside of the while loop?
I thought it could just grab it from the top.

So it doesn’t read anything from outside the loop?

In this example you name all the var instances differently. 1,2,3,4 etc.
But in the while loop you can just name it once and it works.Why is this?