Skip to content

Instantly share code, notes, and snippets.

@brovador
Created April 22, 2018 08:38
Show Gist options
  • Save brovador/fd4b1857a5c5f50b2dfac55e6ea6de4b to your computer and use it in GitHub Desktop.
Save brovador/fd4b1857a5c5f50b2dfac55e6ea6de4b to your computer and use it in GitHub Desktop.
Unity editor script to remove all empty folders from a project. Ideal for cleaning to upload on git repositories
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEditor;
using System.IO;
public class EditorRemoveEmptyFolders {
[MenuItem("Project Tools/Maintenance/Remove Empty Folders")]
public static void RemoveEmptyFolders()
{
var path = Application.dataPath;
List<string> dirsToRemove = new List<string>();
FindDirectoriesToRemove(path, dirsToRemove);
dirsToRemove.Reverse();
foreach (string dir in dirsToRemove) {
if (Directory.Exists(dir)) {
Debug.Log("<color=red>Deleting: " + dir + "</color>");
Directory.Delete(dir, true);
if (File.Exists(dir + ".meta")) {
File.Delete(dir + ".meta");
}
}
}
}
static bool FindDirectoriesToRemove(string path, List<string> dirList)
{
bool hasOnlyMetas = true;
List<string> metaExtensions = new List<string>();
metaExtensions.Add(".meta");
metaExtensions.Add(".ds_store");
foreach (var file in Directory.GetFiles(path)) {
var ext = Path.GetExtension(file).ToLower();
hasOnlyMetas = hasOnlyMetas && metaExtensions.Contains(ext);
if (!hasOnlyMetas) {
break;
}
}
var allSubdirsHasOnlyMetas = true;
foreach (var directory in Directory.GetDirectories(path)) {
var subdirHasOnlyMetas = FindDirectoriesToRemove(directory, dirList);
allSubdirsHasOnlyMetas = allSubdirsHasOnlyMetas && subdirHasOnlyMetas;
}
var result = hasOnlyMetas && allSubdirsHasOnlyMetas;
if (result) {
dirList.Add(path);
}
return result;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment