Unity 获取指定文件夹及其子文件夹下所有文件的方法

在Unity中,我们可以使用System.IO命名空间中的DirectoryFile类来获取指定文件夹及其子文件夹下的所有文件。

一、只获取文件夹下所有文件:

复制代码
using System.Collections.Generic;
using System.IO;
using UnityEngine;

public class FileScanner : MonoBehaviour
{
    public string folderPath; // 指定文件夹路径

    void Start()
    {
        List<string> files = GetFilesInFolder(folderPath);
        foreach (string file in files)
        {
            Debug.Log(file);
        }
    }

    List<string> GetFilesInFolder(string folderPath)
    {
        List<string> files = new List<string>();

        if (Directory.Exists(folderPath))
        {
            string[] currentFiles = Directory.GetFiles(folderPath);
            files.Add(currentFiles);
        }
        else
        {
            Debug.LogWarning("文件夹路径不存在:" + folderPath);
        }

        return files;
    }
}

二、获取文件夹及其子文件夹下所有文件:

复制代码
using System.Collections.Generic;
using System.IO;
using UnityEngine;

public class FileScanner : MonoBehaviour
{
    public string folderPath; // 指定文件夹路径

    void Start()
    {
        List<string> files = GetFilesInFolder(folderPath);
        foreach (string file in files)
        {
            Debug.Log(file);
        }
    }

    List<string> GetFilesInFolder(string folderPath)
    {
        List<string> files = new List<string>();

        if (Directory.Exists(folderPath))
        {
            // 获取当前文件夹下的所有文件
            string[] currentFiles = Directory.GetFiles(folderPath);
            files.Add(currentFiles);

            // 递归获取子文件夹下的所有文件
            string[] subFolders = Directory.GetDirectories(folderPath);
            foreach (string subFolder in subFolders)
            {
                files.Add(GetFilesInFolder(subFolder));
            }
        }
        else
        {
            Debug.LogWarning("文件夹路径不存在:" + folderPath);
        }

        return files;
    }
}
相关推荐
SmalBox3 小时前
【渲染流水线】[逐片元阶段]-[模版测试]以UnityURP为例
unity·渲染
小蜗 strong6 小时前
unity中实现机械臂自主运动
unity·游戏引擎
★YUI★17 小时前
学习游戏制作记录(制作系统与物品掉落系统)8.16
学习·游戏·ui·unity·c#
SmalBox1 天前
【渲染流水线】[逐片元阶段]-[透明度测试]以UnityURP为例
unity·渲染
三只坚果2 天前
blender制作动画导入unity两种方式
unity·游戏引擎·blender
benben0442 天前
《Unity Shader入门精要》学习笔记二
unity·unity shader
YF云飞2 天前
Unity音频管理:打造沉浸式游戏音效
游戏·unity·游戏引擎·游戏程序·个人开发
SmalBox2 天前
【渲染流水线】[逐片元阶段]-[裁剪测试]以UnityURP为例
unity·渲染
与火星的孩子对话2 天前
Unity高级开发:反射原理深入解析与实践指南 C#
java·unity·c#·游戏引擎·lucene·反射
scoone2 天前
开源游戏引擎Bevy 和 Godot
游戏引擎·godot