This code get all the sub folders in a Assets specific folder.
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);
}
}
}
And this get all the prefabs from a specific folder but when I type the folder name :
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);
}
}
}
}
I want to combine both codes so when I make right click and select Get Path it will get all the prefabs from the selected path the right click on the path and the path all sub folders recursive.
Example :
Assets
Folder1
Folder2
Folder3
Folder4
Folder5
Folder6
If in the Assets I make mouse right click on the folder Folder2 and then select from the menu Get Path I want it to get all the prefabs from Folder2 and all the sub folders under Folder2. So In the end I will have a List of all the paths with the folders :
Folder2\1.prefab
Folder2\Folder3\2.prefab
Folder2\Folder3\3.prefab
Folder2\Folder4\4.prefab
In the end my goal is to be able to add to each prefab a component for example a Rigidbody. So if I have a folder with the 10 prefabs and under it 30 sub folders with more 200 prefabs then get all the folders and prefabs and add a component/s to all the prefabs in all folders.