Nested for loop not working as expected

Godot Version

4.2.1

Question

I’m trying to create a simple grid of boxes, however the nested for loop used to instantiate and place the boxes doesn’t seem to execute as expected.

extends Node3D

@export var width: int = 10
@export var depth: int = 10

var box = preload("res://Scenes/Box.tscn")

func _ready():
	for z in depth:
		print_debug("Vertical " + str(z))
		for x in width:
			#Create box instance
			var boxInst: Node = box.instantiate()
			#Position instance
			boxInst.global_position.x = x-(width>>1) #Divide width by 2 and subtract it from x to center
			boxInst.global_position.z = z-(depth>>1) #Divide depth by 2 and subtract it from z to center
			add_child(boxInst) #Add as child
			print_debug("Horizontal " + str(x))

This should create a grid but instead generates a line along the z axis:

If I disable the z loop the boxes align along the x axis. I’m guessing the horizontal boxes are all on x = 0 for some reason

I played a bit with the code and found simple solution:

			boxInst.global_position.x = x-(width>>1) #Divide width by 2 and subtract it from x to center
			add_child(boxInst) #Add as child
			boxInst.global_position.z = z-(depth>>1) #Divide depth by 2 and subtract it from z to center

Instead of assigning the x and z position simultaneously I assign the x position, add it as a child and the add the z position.
I’m guessing something in the backend of Godot is getting a heart attack when having to assign two position changes in such a small amount of time?
Any way it works now:

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