Help loading random resource from a directory of resources

Godot Version

4.2

Question

I’m trying to load a random resource from my directory to be loaded in - I can see a random resource file is found, but I always get two errors -

1- Cannot open file 'res://item2.tres'

2 - Failed loading resource: res://item2.tres. Make sure resources have been imported by opening the project in the editor at least once.

Here’s my code:

	var resource_files = DirAccess.get_files_at("res://Resources/Items/")

	var random_resource = resource_files[randi() % resource_files.size()]
	print(random_resource)
	item.modifiers = load(random_resource)

I’ve tried reimporting everything by deleting the .godot folder, but beyond that not sure what to try. Is it failing because it’s not the absolute path, i.e res://item2.tres instead of res://Resources/Items/item2.tres? If so, why does load only return a relative path and how do I get the absolute path?

Any help would be immensely appreciated - not sure if this is just me being silly and not understanding the filesystem, or if there’s some re-import jank going on.

The problem here is your misunderstanding the DirAccess.get_files_at and the path logic

DirAccess.get_files_at only return the file name without the directory path so you need to join the directory and the file name

	var resource_files = DirAccess.get_files_at("res://Resources/Items/")

	var random_resource = resource_files[randi() % resource_files.size()]
	print(random_resource)
	item.modifiers = load("res://Resources/Items/" + random_resource)
1 Like

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