unity 获取文件夹和子文件夹下面所有预制体
时间: 2024-12-22 15:18:14 浏览: 29
在Unity中,获取文件夹和子文件夹下的所有预制体(Prefab),你可以通过C#脚本来遍历DirectoryInfo和AssetDatabase类。以下是一个基本步骤:
1. 首先,导入所需的命名空间:
```csharp
using UnityEngine;
using System.IO;
using System.Collections.Generic;
using UnityEditor;
```
2. 定义一个递归函数,用于搜索文件夹:
```csharp
public static List<UnityEngine.Object> FindPrefabsInFolder(string folderPath)
{
List<UnityEngine.Object> prefabs = new List<UnityEngine.Object>();
if (!Directory.Exists(folderPath))
return prefabs;
DirectoryInfo dirInfo = new DirectoryInfo(folderPath);
FileInfo[] files = dirInfo.GetFiles("*.prefab");
foreach (FileInfo fileInfo in files)
prefabs.Add(AssetDatabase.LoadMainAssetAtPath(fileInfo.FullName));
// 搜索子目录
DirectoryInfo[] subDirs = dirInfo.GetDirectories();
foreach (DirectoryInfo subdir in subDirs)
prefabs.AddRange(FindPrefabsInFolder(subdir.FullName));
return prefabs;
}
```
3. 调用这个函数并传入你想查找的根目录路径:
```csharp
string rootFolderPath = "Assets/Your/Folder"; // 替换为实际的文件夹路径
List<UnityEngine.Object> allPrefabs = FindPrefabsInFolder(rootFolderPath);
// 现在allPrefabs列表包含了文件夹及其子文件夹下所有的Prefab实例
```
阅读全文