Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save 825i/4108a4c8a1a8489676ae3365d9f204bf to your computer and use it in GitHub Desktop.
Save 825i/4108a4c8a1a8489676ae3365d9f204bf to your computer and use it in GitHub Desktop.
Adds a dropdown option within Unity's Editor to allow the user to one-click delete 'empty’ folders that are still lingering due to a .meta file
using System.IO;
using System.Linq;
using UnityEditor;
using UnityEngine;
public class CleanEmptyFoldersEditorExtension : EditorWindow
{
private static string _deletedFolders;
[MenuItem("Tools/Clean Empty Folders")]
private static void Cleanup()
{
_deletedFolders = string.Empty;
var directoryInfo = new DirectoryInfo(Application.dataPath);
foreach(var subDirectory in directoryInfo.GetDirectories("*.*", SearchOption.AllDirectories))
{
if (subDirectory.Exists)
{
ScanDirectory(subDirectory);
}
}
Debug.Log("Deleted Folders:\n" + (_deletedFolders.Length > 0 ? _deletedFolders : "NONE"));
}
private static string ScanDirectory(DirectoryInfo subDirectory)
{
Debug.Log("Scanning Directory: " + subDirectory.FullName);
var filesInSubDirectory = subDirectory.GetFiles("*.*", SearchOption.AllDirectories);
if (filesInSubDirectory.Length == 0 ||
filesInSubDirectory.All(t => t.FullName.EndsWith(".meta")))
{
_deletedFolders += subDirectory.FullName + "\n";
subDirectory.Delete(true);
var dirMetaFile = subDirectory.FullName + ".meta";
if (File.Exists(dirMetaFile))
{
File.Delete(dirMetaFile);
}
}
return _deletedFolders;
}
}
@Brandon-Gui123
Copy link

Brandon-Gui123 commented Nov 22, 2020

Hey there, thanks for sharing the script! Sorry for the huge delay since I was busy with work that I forgot about this.

I see deletion as a rather destructive action, so in my opinion, I'd like to let users know what will happen if the action is performed, what are the items that would be affected and whether the operation can be reversed.

Just before beginning the deletion, I'd suggest displaying a confirmation dialogue to inform users of the deletion. This is to prevent deletion from happening if the user accidentally selects the option.

Also, I recently noticed that there's a method which can move assets to the trash called AssetDatabase.MoveAssetToTrash which will move both the asset and its .meta file to the operating system's trash bin. If any unfortunate asset gets deleted (hopefully the script won't do that!), it can be restored from the trash bin.

Oh and as a good practice, I'd suggest separating the deletion logic from the scanning logic, so it will be clear that one method does one thing.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment