Skip to content

Instantly share code, notes, and snippets.

@hiulit
Created November 23, 2021 17:18
Show Gist options
  • Save hiulit/772b8784436898fd7f942750ad99e33e to your computer and use it in GitHub Desktop.
Save hiulit/772b8784436898fd7f942750ad99e33e to your computer and use it in GitHub Desktop.
func get_all_files(path: String, file_ext := "", files := []):
var dir = Directory.new()
if dir.open(path) == OK:
dir.list_dir_begin(true, true)
var file_name = dir.get_next()
while file_name != "":
if dir.current_is_dir():
files = get_all_files(dir.get_current_dir().plus_file(file_name), file_ext, files)
else:
if file_ext and file_name.get_extension() != file_ext:
file_name = dir.get_next()
continue
files.append(file_name)
file_name = dir.get_next()
else:
print("An error occurred when trying to access %s." % path)
return files
@wantg
Copy link

wantg commented May 19, 2025

improvement

func get_files(path: String, ext: Variant = null) -> Array[String]:
	var dir_access = DirAccess.open(path)
	var files: Array[String] = []
	for file_name in dir_access.get_files():
		if ext == null || file_name.get_extension() == str(ext):
			files.append(path.path_join(file_name))
	for dir in dir_access.get_directories():
		files.append_array(get_files(path.path_join(dir), ext))
	return files

# get_files("res://")
# get_files("res://", "tscn")

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment