问题描述
string selectedPath = GetPath();
var subFolders = AssetDatabase.GetSubFolders(selectedPath);
List<string> paths = new List<string>();
foreach(string path in subFolders)
{
paths.Add(path);
}
例如,子文件夹为资产/我的文件夹"但是在我的文件夹"下还有更多子文件夹.
For example the subFolders is Assets/My Folderbut under My Folder there are many more subfolders.
AssetDatabase.GetSubFolders不会递归,它只会获取第一个子文件夹.我要递归所有子文件夹.
AssetDatabase.GetSubFolders don't make recursive it's getting the first sub folder only.I want to get all the sub folders recursive.
我尝试过:
列表路径=新的List();foreach(子文件夹中的字符串路径){ path.Add(path);}
List paths = new List();foreach(string path in subFolders){ paths.Add(path);}
但是它仍然只给我第一个子文件夹.
but it's still giving me only the first sub folder.
这就是我如何在Assets中获取所选路径名的方法:
This is how I'm getting the selected path name in the Assets :
[MenuItem("Assets/Get Path")]
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);
}
[MenuItem("Assets/Get Path")]
private static string GetPath()
{
string path = GetClickedDirFullPath();
int index = path.IndexOf("Assets");
string result = path.Substring(index);
return result;
}
推荐答案
您可以使用 List<T>.AddRange
喜欢
You could simply make it recursive using List<T>.AddRange
like
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();
}
例如.
So e.g.
[ContextMenu("Test")]
private void Test()
{
var sb = new StringBuilder();
var folders = SubFolders("Assets");
if(folders.Length > 0)
{
foreach (var folder in SubFolders("Assets"))
{
sb.Append(folder).Append('\n');
}
}
else
{
sb.Append(" << The given path has no subfolders! >>");
}
Debug.Log(sb.ToString());
}
将打印出整个项目的文件夹结构.
will print out the entire project's folder structure.
对于
我知道
Assets/Example 1
Assets/Example 1/SubFolder A
Assets/Example 1/SubFolder B
Assets/Example 1/SubFolder C
Assets/Example 2
Assets/Example 2/SubFolder A
Assets/Example 2/SubFolder A/SubSubFolder A
所以您的情况应该是
So in your case it would be
string selectedPath = GetPath();
var folders = SubFolders(selectedPath);
foreach(var path in folders)
{
...
}
这篇关于如何遍历Assets文件夹中的子文件夹?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!