Delete unused assets in Unreal Engine

This Python-script is used to remove unused assets from the Unreal Engine project.

# This is a sample Python script.

 

# Press Shift+F10 to execute it or replace it with your code.

# Press Double Shift to search everywhere for classes, files, tool windows, actions, and settings.

import os

import sys

import unreal as ue

 

DIRECTORY = '/Game/StarterContent/'

 

editor = ue.EditorAssetLibrary()

 

 

def get_unused_assets(directory):

    unused_assets = []

    is_continue = True

    while is_continue:

        is_continue = False

        assets = editor.list_assets(directory)

        if len(assets) > 0:

            with ue.ScopedSlowTask(len(assets), 'Begin...') as slow_task:

                slow_task.make_dialog(True)

                for asset in assets:

                    dependencies = editor.find_package_referencers_for_asset(asset)

                    if (len(dependencies) == 0 or all_in_array(unused_assets, dependencies) or

                            asset_equal_dependencies(asset, dependencies)) and asset not in unused_assets:

                        is_continue = True

                        unused_assets.append(asset)

                    if slow_task.should_cancel():         # True if the user has pressed Cancel in the UI

                        return

                    slow_task.enter_progress_frame(1)

    return unused_assets

 

 

def all_in_array(array, need):

    for n in need:

        n = n + '.' + os.path.basename(n)

        if n not in array:

            return False

    return True

 

 

def asset_equal_dependencies(asset, dependencies):

    return asset == dependencies[0] + '.' + os.path.basename(dependencies[0])

 

 

def delete(deletes, is_delete=False):

    if not is_delete:

        ue.log('The argument "delete" is required to delete')

    with ue.ScopedSlowTask(len(deletes), 'Delete...') as slow_task:

        for asset in deletes:

            ue.log('DELETE: ' + asset)

            if is_delete:

                editor.delete_asset(asset)

            if slow_task.should_cancel():

                return

            slow_task.enter_progress_frame(1, asset)

 

 

def delete_empty_folders(directory):

    registry = ue.AssetRegistryHelpers().get_asset_registry()

    directories = registry.get_sub_paths(directory, True)

    print(directories)

    for directory in directories:

        if editor.does_directory_exist(directory) and not registry.has_assets(directory):

            ue.log('DELETE DIRECTORY: ' + directory)

            editor.delete_directory(directory)

 

 

# Press the green button in the gutter to run the script.

if __name__ == '__main__':

    delete_assets = get_unused_assets(DIRECTORY)

    if len(sys.argv) > 1:

        arg = sys.argv[1]

        if arg == 'delete':

            delete(delete_assets, True)

            delete_empty_folders(DIRECTORY)

    else:

        delete(delete_assets)