Any way to pick a file from a folder in the project at random?

Godot Version

4.2

Question

Ok, so essentially I have an item system, which has items that are stored as .tres files. they are all stored in a folder. I wanted to cycle through the .tres files and then choose one at random. I have a singleton that holds data about my game’s inventory so if I need to create some sort of registry system for the resources that’s great, but how do I do that?

We use DirAccess to access directory information, such as files in a specific directory. Thus we can write GDScript like this:

var dir_name := "res://my_resources"

# This "open" method returns an instance for accessing your dir
var dir := DirAccess.open(dir_name)
var file_names := dir.get_files()

var resources: Array[Resource] = []
for file_name in file_names:
    resources.append(load(file_name))

One thing to note is that the load function is the same one you always use. Another function you might also be familiar with is preload, also for obtaining resources from a path. However, preload is only for preloading and is not suitable for this situation.

Although I’m currently getting all the resources instead of choosing randomly, the process is straightforward since we can already obtain all of them. We can simply use the Array.pick_random() method:

var dir_name := "res://my_resources"
var dir := DirAccess.open(dir_name)

var file_names := dir.get_files()
var random_file := file_names.pick_random()
var res := load(random_file)

Alternatively, you can use DirAccess.get_files_at() which is a static method version:

var dir_name := "res://my_resources"
var file_names := DirAccess.get_files_at(dir_name)

# Things go exactly the same...
3 Likes

It’s important to remember to set editor/export/convert_text_resources_to_binary to false, If it’s set to true, all resources will be converted to binary on export for optimization, but you won’t be able to load them in the code. I’ve encountered an issue where my project load() improperly after exporting because of this setting.

Please review the following documentation:

1 Like

thank you so much!

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