Hello fellow developers! i need help with this basic roomgen system i made for my platformer roguelike

extends Node2D

@onready var door_exit: Marker2D = $DoorExit

var roomscene1 = preload("res://Scenes/room_1.tscn")
var roomscene2 = preload("res://Scenes/room_2.tscn")

var randroom
var room

func _ready():
	randroom = randi_range(1,2)
	var previous_door = door_exit.global_position
	
		
	if randroom == 1:
		room = roomscene1.instantiate()
	elif randroom == 2:
		room = roomscene2.instantiate()
	
	
	add_child(room)
	
	var new_door = room.get_node("Door")
	room.global_position = previous_door - new_door.position

so the problem here is that after one room it stops, and i have this code in all of the rooms, so this script in the starting room, and the other room variations, so that that one room generates another room that generates another. at least thats what it was supposed to do but it doesnt seem to work. i havent encountered any errors in the debugger, which is weird

I’m no expert, so the only issue I can catch here is that room.global_position = previous_door - new_door.position will always base the room’s global_position based on the new door’s local position relative to its scene.

You need to use global_position for both, like this: room.global_position = previous_door - new_door.global_position.

the thing is that after that when i tried doing that since i also thought it would make sense, but it only offset the rooms weirdly, and when i tried position it worked fine so i just decided to stick with position

That makes sense, your “Door” node is not at the room origin and you want to align the new room’s “Door” node with the previous room’s exit.

You say that the loop stops after one room? Is the loop meant to be the _ready function itself? Each room is supposed to add the next room as soon as the previous room is added to the scene tree?

What is supposed to end the recursion?Are you getting an infinite loop?

The next room’s _ready function will run as soon as you call add_child. At that moment the room’s global_position hasn’t been adjusted yet, so if it then managed to add its own next room in its own _ready function, it wouldn’t be able to set the global position for its next room… And I’m not sure about this, but I think there might be problems adding a child to a scene that was just added in the same frame.

Can you try changing the add_child to call_deferred(“add_child”, room) ?