Last active
October 9, 2023 12:46
-
-
Save liortal53/780075ddb17f9306ae32 to your computer and use it in GitHub Desktop.
Clean Unity project from empty folders
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System.IO; | |
using System.Linq; | |
using UnityEditor; | |
using UnityEngine; | |
public class RemoveEmptyFolders | |
{ | |
/// <summary> | |
/// Use this flag to simulate a run, before really deleting any folders. | |
/// </summary> | |
private static bool dryRun = true; | |
[MenuItem("Tools/Remove empty folders")] | |
private static void RemoveEmptyFoldersMenuItem() | |
{ | |
var index = Application.dataPath.IndexOf("/Assets"); | |
var projectSubfolders = Directory.GetDirectories(Application.dataPath, "*", SearchOption.AllDirectories); | |
// Create a list of all the empty subfolders under Assets. | |
var emptyFolders = projectSubfolders.Where(path => IsEmptyRecursive(path)).ToArray(); | |
foreach (var folder in emptyFolders) | |
{ | |
// Verify that the folder exists (may have been already removed). | |
if (Directory.Exists (folder)) | |
{ | |
Debug.Log ("Deleting : " + folder); | |
if (!dryRun) | |
{ | |
// Remove dir (recursively) | |
Directory.Delete(folder, true); | |
// Sync AssetDatabase with the delete operation. | |
AssetDatabase.DeleteAsset(folder.Substring(index + 1)); | |
} | |
} | |
} | |
// Refresh the asset database once we're done. | |
AssetDatabase.Refresh(); | |
} | |
/// <summary> | |
/// A helper method for determining if a folder is empty or not. | |
/// </summary> | |
private static bool IsEmptyRecursive(string path) | |
{ | |
// A folder is empty if it (and all its subdirs) have no files (ignore .meta files) | |
return Directory.GetFiles(path).Select(file => !file.EndsWith(".meta")).Count() == 0 | |
&& Directory.GetDirectories(path, string.Empty, SearchOption.AllDirectories).All(IsEmptyRecursive); | |
} | |
} |
Thanks for the input! I extended it for auto deletion, show and remove empty folders.
https://gist.github.com/mrwellmann/c9c6bc416143a58d734077ffe57179a3
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thanks for this Gist. Was seeing a some issues in regards to finding the correct folders to remove. The fixed IsEmptyRecursive below: