How to instance scenes in a for loop?

Godot Version

V 4.6.1

Question

I tried to use a for loop to place boxes in a row, with the same y axis but the code always places the boxes in the last loop (in the location the last box should be in)

extends Node

var coord := Vector2(20, 300)

var box_scene = preload("res://scenes/box.tscn")

func _ready() -> void:
	var box = box_scene.instantiate()
	for i in 5:
		coord.x += 100
		add_child(box)
		box.position = coord

You are only instantiating one box, if you move your var box into the for loop it will instantiate 5 boxes

func _ready() -> void:
	for i in 5:
		var box = box_scene.instantiate()
		coord.x += 100
		add_child(box)
		box.position = coord
5 Likes

You need to do instantiate each iteration, you’re using the same node

3 Likes