Erase function wont remove the item?

Godot Version

4.3

Question

I’m trying to get this code to remove the array item that correlates with the instance_room variable, however, the erase function is not doing that properly? I think this may have to do with it being initialized. The code is as follows:

extends Node3D


# Called when the node enters the scene tree for the first time.
func _ready():
	var rooms = [preload("res://Generation/House/rooms/rat_room.tscn"), preload("res://Generation/House/rooms/small_room.tscn"), preload("res://Generation/House/rooms/medium_room.tscn"),
	preload("res://Generation/House/rooms/long_room.tscn"), preload("res://Generation/House/rooms/Large_room.tscn")]
	var exits = []
	
	for child in $".".get_children():
		exits.append(child)
	print(exits)
	for i in exits:
		var current_exit = i
		print(current_exit)
		var current_location = current_exit.global_position
		print(current_location)
		var current_orientation = current_exit.global_rotation
		print("rotation", current_orientation)
		var instance_room = rooms[randi() % rooms.size()].instantiate()
		instance_room.set_position(current_location)
		instance_room.set_rotation(current_orientation)
		add_child(instance_room)
		print("Spawning room:", instance_room)
		rooms.erase(instance_room)
		print(rooms)
		#pass
	return rooms


# Called every frame. 'delta' is the elapsed time since the previous frame.
func _process(_delta: float) -> void:
	pass

instance_room is an instantiated room, not the PackedScene resource that your rooms array contains. You’d have to store the randomly found element before using .instantiate()

I did that but now I’m getting a “Modulo by zero error in operator %”.

You would have to post your updated code, I’m not sure how you got to that error.

I was recommending these changes

+ var selected_room = rooms.pick_random()
~ var instance_room = selected_room.instantiate()
  instance_room.set_position(current_location)
  instance_room.set_rotation(current_orientation)
  add_child(instance_room)
  print("Spawning room:", instance_room)
~ rooms.erase(selected_room)

I added the code you suggested, but now it’s getting a nill error when instantiating selected_room. The error says “Can’t take value from empty array”.

You’ve run out of rooms to spawn, they’ve all been erased. How would you like to resolve this? Stop the for loop, ignoring all remaining exits? Should you re-populate the rooms array?

Thanks, that was the issue. The loop should work properly now.