How to add multiple instanced children at the same time?

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

My code looks like this:

onready var amount = 20
onready var coin = preload("res://coin.tscn").instance()

func _drop():

		for i in range(amount):
			amount -= 1
			get_parent().add_child(coin)
			print("coin")
			
	pass

When this func is executed, it prints “coin” 20 times, but only add one child instance.

What do I have to do to add 20 children?

Thank you.

1 Like
:bust_in_silhouette: Reply From: whiteshampoo

Try this: (untested)

onready var amount = 20
onready var coin = preload("res://coin.tscn")

func _drop():

        for i in range(amount):
            var new_coin = coin.instance()
            get_parent().add_child(new_coin)
            print("coin: ", new_coin.name)
            # the nodename might help to debug

    pass

I dont think you want to decrease amount in the loop. This will probaly give you bugs, if you use _drop() a second time.

I’m also not sure, if you need “onready” for these variables.

It worked. Thank you!

gubbebubbe | 2020-05-11 11:09

1 Like