Level loading code doesn't work on export

Godot Version

4.2.2

Question

Hello! I have the following code in my game that works in-engine, but breaks on export (levels don’t load in the debug export, and the game crashes in the non-debug export).

Relevant code in the level select:

func load_levels():
	var folder = DirAccess.open("res://PuzzleGame/Levels/")
	if folder:
		folder.list_dir_begin()
		var file_name = folder.get_next()
		while file_name != "":
			if !folder.current_is_dir():
				var file_path = folder.get_current_dir() + "/" + file_name
				levels.append(load(file_path))
			file_name = folder.get_next()

func new_level_picked(index : int):
	for child in level_container.get_children():
		child.get_child(0).set_to_default()
	level_picked.emit(index)
	level_full.unload_current_level()
	level_full.load_new_level(levels[index - 1])

Relevant code in the level loader:

func load_new_level(level : PackedScene):	
	timer.reset_timer()
	timer.stop_timer()
	var new_level = level.instantiate()
	new_level.you_win.connect(level_win)
	new_level.you_lose.connect(level_lose)
	add_child(new_level)
	current_level = new_level
	current_level.movement_not_allowed = true
	level_ready()

func unload_current_level():
	if current_level:
		current_level.queue_free()
		for child in hearts_container.get_children():
			child.queue_free()
		hearts_display = []
		timer.reset_timer()

func level_ready():
	var player = current_level.get_node("Player")
	player.how_was_the_fall.connect(update_health)
	for i in range(player.max_health / 2):
		var new_heart = HEART.instantiate()
		hearts_container.add_child(new_heart)
		hearts_display.append(new_heart)
		#new_heart.visible = false
	level_loaded.emit()

What should I change to make it work in the exported version? If you need more code or information, let me know!

Would be grateful for any help!

When you add a Resource (texture, sound, model,…) to your game godot will import it in a better suited format internally (inside the .godot/imported folder) and the original files won’t be added to the pck file when exporting the game as they aren’t needed.

The same happens with text Resourceslike *.tscn (scenes) or *.tres (other Resource types). They will be converted to binary files (they are originally human readable text files) when exporting the game unless you uncheck the editor/export/convert_text_resources_to_binary in the Project Settings (It’s enabled by default).

FileAccess has no knowledge about this so it won’t follow the *.remap/*.import files in the exported game. You’ll need to check the extension of the level files and remove it before appending them to the array.

In Godot 4.4 ResourceLoader.list_directory() was added to avoid doing all that manually.

2 Likes