这段代码获取了指定 Assets 文件夹内的所有子文件夹。
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using UnityEditor;
using UnityEngine;
public class AddComponents : Editor
{
private static string GetClickedDirFullPath()
{
string clickedAssetGuid = Selection.assetGUIDs[0];
string clickedPath = AssetDatabase.GUIDToAssetPath(clickedAssetGuid);
string clickedPathFull = Path.Combine(Directory.GetCurrentDirectory(), clickedPath);
FileAttributes attr = File.GetAttributes(clickedPathFull);
return attr.HasFlag(FileAttributes.Directory) ? clickedPathFull : Path.GetDirectoryName(clickedPathFull);
}
private static string GetPath()
{
string path = GetClickedDirFullPath();
int index = path.IndexOf("Assets");
string result = path.Substring(index);
return result;
}
private static string[] GetSubFoldersRecursive(string root)
{
var paths = new List<string>();
// If there are no further subfolders then AssetDatabase.GetSubFolders returns
// an empty array => foreach will not be executed
// This is the exit point for the recursion
foreach (var path in AssetDatabase.GetSubFolders(root))
{
// add this subfolder itself
paths.Add(path);
// If this has no further subfolders then simply no new elements are added
paths.AddRange(GetSubFoldersRecursive(path));
}
return paths.ToArray();
}
[MenuItem("Assets/Get Folders")]
private static void GetFolders()
{
List<string> paths = new List<string>();
string selectedPath = GetPath();
var folders = GetSubFoldersRecursive(selectedPath);
foreach (var path in folders)
{
paths.Add(path);
}
}
}
以下代码可从指定文件夹中获取所有预制体,但是当我输入文件夹名称时:
public List<string> prefabsPaths;
public void AddComponentsToObjects()
{
prefabsPaths = new List<string>();
string[] assetsPaths = AssetDatabase.GetAllAssetPaths();
foreach (string assetPath in assetsPaths)
{
if (assetPath.Contains("Archanor"))
{
if (assetPath.Contains("Prefabs"))
{
prefabsPaths.Add(assetPath);
}
}
}
}
我希望将两个代码合并,这样当我右键单击并选择“获取路径”时,它将获取所选路径中的所有prefab,包括右键单击的路径和该路径下的所有子文件夹(递归获取)。
示例:
Assets
Folder1
Folder2
Folder3
Folder4
Folder5
Folder6
如果我在资源中右键单击文件夹Folder2,然后从菜单中选择“获取路径”,我希望它能获取Folder2中所有预制件以及Folder2下的所有子文件夹。最终,我将获得包含所有文件夹路径的列表:
Folder2\1.prefab
Folder2\Folder3\2.prefab
Folder2\Folder3\3.prefab
Folder2\Folder4\4.prefab
最终目标是为每个预制件添加一个组件,例如Rigidbody。 因此,如果我有一个包含10个预制件的文件夹,并且其中有30个子文件夹和200多个预制件,则获取所有文件夹和预制件并在所有文件夹中的所有预制件上添加一个或多个组件。