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;
    }
}
相关推荐
世洋Blog2 小时前
SiYangUnityEventSystem,一个Unity中的事件系统
观察者模式·unity·c#·游戏引擎·事件系统
呆呆敲代码的小Y2 小时前
【Unity实战篇】| 游戏滑动框添加特殊效果,如实时高亮显示、曲线滑动等
游戏·unity·游戏引擎·实战·u3d·免费游戏·unity实战技巧
Tatalaluola3 小时前
【Quest开发】用unity UI快速实现交互
unity·游戏引擎
技术小甜甜3 小时前
[Godot] 在 Godot 3.1 中配置 ADB 可执行文件的实用指南
游戏·adb·游戏引擎·godot
技术小甜甜3 小时前
【Godot】【入门】Godot 是什么?适合做哪些类型的游戏(附路线图+避坑清单)
游戏·游戏引擎·godot
码界奇点4 小时前
Unity WebGL输入支持终极指南解决浏览器输入难题的完整方案
unity·容器·游戏引擎·鸿蒙系统·webgl
90后小陈老师4 小时前
Unity动画控制
unity·游戏引擎
Miss_SQ15 小时前
Webgl打包后删除StreamingAssets文件夹下多余资源
unity·c#·webgl
Monkey_Xuan19 小时前
C#中的引用传递和值传递
unity·c#
CreasyChan19 小时前
C# LINQ 深度解析:优缺点与性能陷阱
unity·c#·游戏开发