删除无用的asset
已经在地图中使用的asset会有asset reference
EditorAssetLibrary(按F12)open header file,会有如下一个功能,可以找asset reference,返回bool值
UFUNCTION(BlueprintCallable, Category = "Editor Scripting | Asset")
static TArray<FString> FindPackageReferencersForAsset(const FString& AssetPath, bool bLoadAssetsToConfirm = false);
for (const FAssetData& SelectedAssetData : SelectedAssetsData)
是一个范围循环(range-based for loop),通常在 Unreal Engine 中用于遍历一个容器中的所有元素。
: 在 for 循环中的用法是用于范围循环(range-based for loop)的语法符号。“在”或者“属于”
ObjectTools.h中的非强制删除。可以让使用者有一个确认删除的机会。
UNREALED_API int32 DeleteAssets( const TArray<FAssetData>& AssetsToDelete, bool bShowConfirmation = true );
如下报错(unresolved external symbal) means we need to add module to Build.cs file
UnrealEd means Unreal Editor
PublicDependencyModuleNames.AddRange(
new string[]
{
"Core","Blutility","EditorScriptingUtilities","UMG","Niagara","UnrealEd"
// ... add other public dependencies that you statically link with here ...
}
);
示例代码
UFUNCTION(CallInEditor)
void RemoveUnusedAssets();
// Fill out your copyright notice in the Description page of Project Settings.
#include "AssetAction/QuickAssetAction.h"
#include "DebugHeader.h"
#include "EditorUtilityLibrary.h"
#include "EditorAssetLibrary.h"
#include "ObjectTools.h" //新增
void UQuickAssetAction::RemoveUnusedAssets()
{
TArray<FAssetData> SelectedAssetsData = UEditorUtilityLibrary::GetSelectedAssetData();
TArray<FAssetData> UnusedAssetsData;
for (const FAssetData& SelectedAssetData : SelectedAssetsData)
{
TArray<FString> AssetReferencers =
UEditorAssetLibrary::FindPackageReferencersForAsset(SelectedAssetData.ObjectPath.ToString());
if (AssetReferencers.Num() == 0) {
UnusedAssetsData.Add(SelectedAssetData);
}//把它加入废物列表
}
if (UnusedAssetsData.Num() == 0) {
ShowMsgDialog(EAppMsgType::Ok, TEXT("No unused asset found among selected assets"), false);
return;
}
else {
const int32 NumOfAssetsDeleted = ObjectTools::DeleteAssets(UnusedAssetsData);//执行删除
ShowNotifyInfo(TEXT("Successfully deleted " + FString::FromInt(NumOfAssetsDeleted) + TEXT(" unused assets.")));
}
//const int32 NumOfAssetDeleted = ObjectTools::DeleteAssets(UnusedAssetsData);//执行删除
//if (NumOfAssetDeleted == 0)return;
//ShowNotifyInfo(TEXT("Successfully deleted " + FString::FromInt(NumOfAssetsDeleted) + TEXT(" unused assets.")));
}
可读性:可以考虑将未使用资产的查找和删除逻辑分成两个独立的函数