muscly / UnityCleanEmptyDirectories

Unity Asset that cleans all empty directories.
34 stars 11 forks source link

Triggered every time an asset is imported #3

Open OrionFive opened 6 years ago

OrionFive commented 6 years ago

It seems that if "clean on save" is on, directory cleaning is triggered every time a new asset is imported. In my case, if I add 10 new assets, it takes about 20 seconds before Unity is responsive again.

But here's the fix too:

    static bool triggered;
    // UnityEditor.AssetModificationProcessor
    public static string[] OnWillSaveAssets(string[] paths)
    {
        if (CleanOnSave)
        {
            triggered = true;
            EditorApplication.delayCall += Clean;
        }

        return paths;
    }

    private static void Clean()
    {
        // Only run once
        if (!triggered) return;
        triggered = false;

        List<DirectoryInfo> emptyDirs;
        FillEmptyDirList(out emptyDirs);
        if (emptyDirs != null && emptyDirs.Count > 0)
        {
            DeleteAllEmptyDirAndMeta(ref emptyDirs);

            Debug.Log("[Clean] Cleaned Empty Directories on Save");

            if (OnAutoClean != null) OnAutoClean();
        }
    }

This way it will only run once, no matter how often Unity calls "OnWillSaveAssets".

OrionFive commented 6 years ago

Further, by writing

    // UnityEditor.AssetModificationProcessor
    public static string[] OnWillSaveAssets(string[] paths)
    {
        if (CleanOnSave && paths.Any(p => p.EndsWith(".asset")))
        {
            triggered = true;
            EditorApplication.delayCall += Clean;
        }

        return paths;
    }

it will only run when an actual scene (or ScriptableObject) is saved, and not every time any asset is imported.