Topic was automatically imported from the old Question2Answer platform.
Asked By
Karl Wilhelm
I have an AnimatedSprite node, in which I want to load all .png files from a folder, and add them as frames. So before I can add them as frames I try to use this code to create a list of all files. But when I run this code, it only returns an endless stream of “Found dir: .”, which I assume is the current directory?
extends AnimatedSprite
func _ready():
dir_contents('res://assets/planets')
func dir_contents(path):
var dir = Directory.new()
if dir.open(path) == OK:
dir.list_dir_begin()
var file_name = dir.get_next()
while file_name != "":
if dir.current_is_dir():
print('Found dir: ' + file_name)
else:
print('Found file: ' + file_name)
file_name = dir.get_next()
else:
print("An error occurred when trying to access the path.")
This code works well for me and supports loading resources in exported builds
func get_all_in_folder(path):
var items = []
var dir = DirAccess.open(path)
if not dir:
push_error("Invalid dir: " + path)
return items # Return an empty list if the directory is invalid
# print("Opening directory: ", path)
dir.list_dir_begin()
var file_name = dir.get_next()
while file_name != "":
# print("Found file: ", file_name)
if !file_name.begins_with(".") and !file_name.ends_with(".import"):
var full_path = path + "/" + file_name
# Remove .remap extension if present
if full_path.ends_with(".remap"):
full_path = full_path.substr(0, full_path.length() - 6)
# print("Checking path: ", full_path)
if ResourceLoader.exists(full_path):
# print("Path exists: ", full_path)
var res = ResourceLoader.load(full_path)
if res:
# print("Loaded resource: ", full_path)
items.append(res)
else:
push_error("Failed to load resource: ", full_path)
else:
push_error("Resource does not exist: ", full_path)
file_name = dir.get_next()
dir.list_dir_end()
return items