GDScript:扫描一个目录并获取文件列表(可递归)

代码

把它写成一个静态方法,开箱即用

class_name FileHelper

static func scan(path:String) -> Array:
	var file_name := ""
	var files := []
	var dir := Directory.new()
	if dir.open(path) != OK:
		print("Failed to open:"+path)
	else:
		dir.list_dir_begin(true)
		file_name = dir.get_next()
		while file_name!="":
			if dir.current_is_dir():
				var sub_path = path+"/"+file_name
				files += scan(sub_path)
			else:
				var name := path+"/"+file_name
				files.push_back(name)
			file_name = dir.get_next()
		dir.list_dir_end()
	return files

测试输出
[
res://Game/Commons/Prefabs/Camera/CameraMan.gd, 
res://Game/Commons/Prefabs/Camera/CameraShaker.gd, 
res://Game/Commons/Prefabs/Camera/CameraStates/FollowState.gd,
res://Game/Commons/Prefabs/Camera/camera_man.tscn
]

你可能感兴趣的:(Godot笔记,#,Godot,实践,Godot,GDScript,扫描目录,游戏开发,文件列表)