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

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

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

复制代码
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;
    }
}
相关推荐
WarPigs11 小时前
Unity无法修改Assembly-CSharp.csproj错误
unity
FairGuard手游加固1 天前
手游加固怎么做?SO、IL2CPP、AssetBundle 与运行时保护详解
安全·游戏·unity
阿松爱学习2 天前
【Unity开发】监听Scene场景事件
unity·c#
xiaogai_gai3 天前
BOM 物料清单同步实战:金蝶云星空 → 四化智造 MES 修改场景深度拆解
unity·游戏引擎
淡海水3 天前
03-03-架构篇-SGen GC架构解析
unity·架构·c#·gc·sgen
/**书香门第*/3 天前
Cocos Creator 打螺丝游戏的实现
游戏引擎·cocos2d·螺丝·打螺丝
萌萌的提莫队长4 天前
Unity相机捕捉,图像识别,抠像+合成
opencv·unity
mxwin4 天前
Unity Shader 光线追踪原理与实战案例
unity·游戏引擎
地狱为王5 天前
Unity使用DPDFNet实现实时语音增强(降噪)
unity·语音增强·降噪·dpdfnet
平行云PVT5 天前
国产信创实时云渲染解决方案:如何实现数字孪生与三维应用云化部署?
unity·webrtc·unreal engine·实时云渲染·国产信创·摩尔线程·砺算科技