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;
    }
}
相关推荐
SmalBox17 小时前
【光照】[自发光Emission]以UnityURP为例
unity·渲染
SmalBox2 天前
【光照】Unity中的[经验模型]
unity·渲染
萘柰奈2 天前
Unity学习----【进阶】TextMeshPro学习(三)--进阶知识点(TMP基础设置,材质球相关,两个辅助工具类)
学习·unity
Yasin Chen2 天前
Unity UI坐标说明
ui·unity
应用市场2 天前
无人机姿态控制系统详解与实现
游戏引擎·cocos2d
陈言必行2 天前
Unity 性能优化 之 编辑器创建资源优化( 工作流 | 场景 | 预制体)
unity·编辑器·游戏引擎
1uther2 天前
Unity核心概念⑨:Screen
开发语言·游戏·unity·c#·游戏引擎
死也不注释3 天前
【Unity UGUI 交互组件——Slider(7)】
unity·游戏引擎·交互
程序猿多布3 天前
XLua教程之热补丁技术
unity·c#·lua·xlua
SmalBox3 天前
【光照】Unity中的[光照模型]概念辨析
unity·渲染