Skip to content

Instantly share code, notes, and snippets.

@liortal53
Last active October 9, 2023 12:46
Show Gist options
  • Save liortal53/780075ddb17f9306ae32 to your computer and use it in GitHub Desktop.
Save liortal53/780075ddb17f9306ae32 to your computer and use it in GitHub Desktop.
Clean Unity project from empty folders
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);
}
}
@DennisTT
Copy link

DennisTT commented Sep 9, 2016

Thanks for this Gist. Was seeing a some issues in regards to finding the correct folders to remove. The fixed IsEmptyRecursive below:

return Directory.GetFiles(path).Where(file => !file.EndsWith(".meta")).Count() == 0
    && Directory.GetDirectories(path, "*", SearchOption.AllDirectories).All(IsEmptyRecursive);
  1. Changed .Select() to .Where() for filtering the files.
  2. Changed the empty string filter to wildcard * for retrieving the directories.

@mrwellmann
Copy link

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