Created
November 23, 2021 17:18
-
-
Save hiulit/772b8784436898fd7f942750ad99e33e to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
Upgraded version for godot 4.x
func get_all_files(path: String, file_ext := "", files := []):
var dir = DirAccess.open(path)
if DirAccess.get_open_error() == OK:
dir.list_dir_begin()
var file_name = dir.get_next()
while file_name != "":
if dir.current_is_dir():
files = get_all_files(dir.get_current_dir() +"/"+ file_name, file_ext, files)
else:
if file_ext and file_name.get_extension() != file_ext:
file_name = dir.get_next()
continue
files.append(dir.get_current_dir() +"/"+ file_name)
file_name = dir.get_next()
else:
print("An error occurred when trying to access %s." % path)
return files
still works (godot4.2) + small improvement
## returns list of files at given path recursively
## [br]taken from - https://gist.github.com/hiulit/772b8784436898fd7f942750ad99e33e
static func get_all_files(path: String, file_ext := "", files : Array[String] = []) -> Array[String]:
var dir : = DirAccess.open(path)
if file_ext.begins_with("."): # get rid of starting dot if we used, for example ".tscn" instead of "tscn"
file_ext = file_ext.substr(1,file_ext.length()-1)
if DirAccess.get_open_error() == OK:
dir.list_dir_begin()
var file_name = dir.get_next()
while file_name != "":
if dir.current_is_dir():
# recursion
files = get_all_files(dir.get_current_dir() +"/"+ file_name, file_ext, files)
else:
if file_ext and file_name.get_extension() != file_ext:
file_name = dir.get_next()
continue
files.append(dir.get_current_dir() +"/"+ file_name)
file_name = dir.get_next()
else:
print("[get_all_files()] An error occurred when trying to access %s." % path)
return files
use like this:
var level_scenes := FileUtils.get_all_files(levels_folder_path, ".tscn")
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
If you want the full path of the file instead of just the name, change:
Line 17
for