给特定类型资源添加右键菜单选项

有些需求,需要在 UE 的 Content Browser 里给某些资源添加一些处理功能,希望能直接选中右键进行处理。
UE 中提供了这样的方式,用于扩展某种类型资源的右键菜单,需要继承自FAssetTypeActions_Base

.h
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
#pragma once
#include "CoreMinimal.h"
#include "Engine/StaticMesh.h"
#include "Toolkits/IToolkitHost.h"
#include "AssetTypeActions_Base.h"
#include "Engine/PrimaryAssetLabel.h"

struct FToolMenuSection;
class FMenuBuilder;

class FAssetTypeActions_PrimaryAssetLabel : public FAssetTypeActions_Base
{
public:
// IAssetTypeActions Implementation
virtual FText GetName() const override { return NSLOCTEXT("AssetTypeActions", "AssetTypeActions_PrimaryAssetLabel", "Primary Asset Label"); }
virtual FColor GetTypeColor() const override { return FColor(0, 255, 255); }
virtual UClass* GetSupportedClass() const override { return UPrimaryAssetLabel::StaticClass(); }
virtual bool HasActions(const TArray<UObject*>& InObjects ) const override { return true; }
virtual void GetActions(const TArray<UObject*>& InObjects, FToolMenuSection& Section) override;
// virtual void OpenAssetEditor(const TArray<UObject*>& InObjects, TSharedPtr<class IToolkitHost> EditWithinLevelEditor = TSharedPtr<IToolkitHost>() ) override;
virtual uint32 GetCategories() override { return EAssetTypeCategories::Basic; }
// virtual class UThumbnailInfo* GetThumbnailInfo(UObject* Asset) const override;
virtual bool IsImportedAsset() const override { return true; }
// virtual void GetResolvedSourceFilePaths(const TArray<UObject*>& TypeAssets, TArray<FString>& OutSourceFilePaths) const override;
};

其中最关键的是重写 GetSupportedClass 返回想要添加到哪种资源的右键菜单里。

.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
void FAssetTypeActions_PrimaryAssetLabel::GetActions(const TArray<UObject*>& InObjects,
FToolMenuSection& Section)
{
auto Labels = GetTypedWeakObjectPtrs<UPrimaryAssetLabel>(InObjects);
Section.AddMenuEntry(
"ObjectContext_AddToPatchIncludeFilters",
NSLOCTEXT("AssetTypeActions_PrimaryAssetLabel", "ObjectContext_AddToPatchIncludeFilters", "Add To Patch Include Filters"),
NSLOCTEXT("AssetTypeActions_PrimaryAssetLabel", "ObjectContext_AddToPatchIncludeFiltersTooltip", "Add the label to HotPatcher Include Filters."),
FSlateIcon(),
FUIAction(
FExecuteAction::CreateSP(this, &FAssetTypeActions_PrimaryAssetLabel::ExecuteAddToPatchIncludeFilter, Labels)
));
Section.AddMenuEntry(
"ObjectContext_AddToChunkConfig",
NSLOCTEXT("AssetTypeActions_PrimaryAssetLabel", "ObjectContext_AddToChunkConfig", "Add To Chunk Config"),
NSLOCTEXT("AssetTypeActions_PrimaryAssetLabel", "ObjectContext_AddToChunkConfigTooltip", "Add Label To Chunk Config"),
FSlateIcon(),
FUIAction(
FExecuteAction::CreateSP(this, &FAssetTypeActions_PrimaryAssetLabel::ExecuteAddToChunkConfig, Labels)
));
}

在绑定的事件里可以处理对资源的操作流程。

最后,需要把所写的这个类注册到 AssetTools 里,可以写到 Module 的 StartupModule 中:

1
FAssetToolsModule::GetModule().Get().RegisterAssetTypeActions(MakeShareable(new FAssetTypeActions_PrimaryAssetLabel));

效果: