How to import all files from a folder

Godot Version 4.3 Beta 1

Question

All files are of the same Resource type, I would like to import each file from a folder automatically, that is, without having to specify a specific file name all the time, but just have it import everything in a row until it runs out of files, how do I do this?

P.S. I want to put all files in a dictionary storing <string, Resource>
In this case, the string key is the name of the resource, and its value is the resource itself

It’s unclear what you are trying to accomplish. Why can’t these be imported from the editor?

You can check my method to this right here. File ui/presets_panel.gd, function _populate_preset_tree. You just loop over all files and load them as resources. You can set the filename as a dictionary key for your use case.

I want to import every file in this folder

изображение

But in the script, do not write the path for each file, and import all in order.

Pseudocode:

Folder Resources = Open(".../Resources")
Dictionary<string, Resource> DICT
for File in Resources:
    DICT[File.Name] = (File as Resource)

Thanks, I’ll give it a try and let you know if I figure it out

Thanks, I figured out your code and was able to write my own. By the way, I was writing in C# and here is the code:

It creates a dictionary that will be loaded with each resource from the folder
public static Dictionary<string, Resource> LoadResources(string path)
{
    Dictionary<string, Resource> resources = new Dictionary<string, Resource>();

    DirAccess dir_access = DirAccess.Open(path);
    if (dir_access == null) { return null; }

    string[] files = dir_access.GetFiles();
    if (files == null) { return null; }

    foreach(string file_name in files)
    {
        Resource loaded_resource = GD.Load<Resource>(path + file_name);
        if (loaded_resource == null) { continue; }

        resources[file_name] = loaded_resource;
    }

    return resources;
}

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