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;
    }
}
相关推荐
淡海水1 小时前
11-04-Unity-Span-foreach-LINQ的分配与热路径边界
unity·c#·linq·foreach·span
狂人开飞机10 小时前
23、实战平台跳跃游戏
游戏·游戏引擎·godot
灸木18 小时前
Unity 多线程与并发:什么时候该用多线程?
unity
淡海水1 天前
11-02-Unity-Mono-vs-IL2CPP-两种脚本后端的数据结构行为差异
数据结构·unity·游戏引擎·il2cpp·mono
彧azz1 天前
初学Unity:编辑器
笔记·学习·unity·游戏引擎
小小数媒成员1 天前
GPU优化(1)
游戏·unity·游戏引擎
淡海水1 天前
11-03-Unity-List-T-和Dictionary-TKey-TValue-的性能调优实战
算法·unity·c#·list·dictionary
狂人开飞机1 天前
27、实战物理益智游戏
游戏·游戏引擎·godot
小小数媒成员2 天前
如何优化代码适应托管内存?
游戏·unity·游戏引擎