Load file from all subdirectories in the directory (mods logic)

Godot Version

Godot 4.2.1 Linux x86_64

Question

I want the mods folder to be next to the used game file. There will be subfolders with
mod.json file in them. How can I do this using the standard Godot tools with GDScript?

More specifically I need answers to the questions:
How to load files not only from ‘res://’ or ‘user://’?
How to get all subfolders in a certain folder?
How to read files correctly?

I need the user to be able to upload his mod to the mods folder and the game will read it without problems, for now only the name of the mod will suffice. Like file:

mods/test_mod/mod.json

{
    "name": "Test mod"
}

You can get the path to where the executable is with OS.get_executable_path()

To list the folders, subfolders and files you’ll need to use the DirAccess class. You can read the documentation to know more.

To read the files you will need to use the FileAccess class. You can read the documentation to know more.

1 Like

I’m trying to copy some codes from the wiki, but it doesn’t work. Maybe you know what the reason is? There is code:

func reload_mods():
	was_mod_loaded = false
	loaded_mods = []
	
	var mods_path = OS.get_executable_path() + "/" + MODS_DIRECTORY_NAME
	
	var dir = DirAccess.open(mods_path)
	
	# Iterate mods
	if dir:
		dir.list_dir_begin()
		var file_name = dir.get_next()
		while file_name != "":
			if dir.current_is_dir():
				_load_mod(file_name)
			else:
				print("Found file: " + file_name)
			file_name = dir.get_next()
	else:
		print("An error occurred when trying to access the path.")
	
	was_mod_loaded = true

func _load_mod(file_name):
	print("Try load mod: " + file_name)

I got print message → ‘An error occurred when trying to access the path.’

MODS_DIRECTORY_NAME is variable:
const MODS_DIRECTORY_NAME: String = "mods"

The directory probably does not exist. You’ll need to check that the directory exists first. Something like:

	else:
		print("An error occurred when trying to access the path: %s" % error_string(DirAccess.get_open_error()))

Should give you the error you are getting.

Now the message looks like this : An error occurred when trying to access the mods path: Invalid parameter

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