写出ue5的c++代码 以增加资源查看的上下文菜单
时间: 2024-05-01 18:16:49 浏览: 230
以下是UE5的C++代码示例,用于增加资源查看的上下文菜单:
```cpp
#include "CoreMinimal.h"
#include "LevelEditor.h"
#include "Editor/UnrealEd/Public/Editor.h"
#include "Editor/UnrealEd/Public/EditorStyleSet.h"
#include "Editor/UnrealEd/Public/LevelEditorContextMenuContext.h"
#include "Editor/UnrealEd/Public/Toolkits/AssetEditorToolkit.h"
#include "Editor/UnrealEd/Public/Toolkits/ToolkitManager.h"
#include "Editor/UnrealEd/Public/Toolkits/AssetEditorManager.h"
void OnContextMenuOpened(const TSharedRef<FUICommandList> CommandList, TArray<FLevelEditorContextMenuContext>& Contexts)
{
for (const FLevelEditorContextMenuContext& Context : Contexts)
{
if (Context.AssetName.IsEmpty())
{
continue;
}
const FString CommandName = FString::Printf(TEXT("OpenAssetInViewer_%s"), *Context.AssetName);
FUIAction OpenAssetInViewerAction(FExecuteAction::CreateLambda([=]()
{
UAssetEditorSubsystem* AssetEditorSubsystem = GEditor->GetEditorSubsystem<UAssetEditorSubsystem>();
if (AssetEditorSubsystem)
{
FAssetEditorToolkit* AssetEditorToolkit = AssetEditorSubsystem->FindEditorForAsset(Context.Object);
if (!AssetEditorToolkit)
{
const FAssetEditorManager& AssetEditorManager = FAssetEditorManager::Get();
FAssetEditorToolkitCreationOptions Options;
Options.HostMode = EToolkitMode::Standalone;
Options.RequestBringToFront = true;
AssetEditorToolkit = AssetEditorManager.OpenEditorForAsset(Context.Object, Options);
}
if (AssetEditorToolkit)
{
AssetEditorToolkit->BringToFront();
}
}
}));
const FText CommandLabel = FText::Format(NSLOCTEXT("OpenAssetInViewerCommands", "OpenAssetInViewerCommand_Label", "Open {0} in Viewer"), FText::FromString(Context.AssetName));
const FText CommandDescription = FText::Format(NSLOCTEXT("OpenAssetInViewerCommands", "OpenAssetInViewerCommand_Description", "Opens {0} in the asset viewer"), FText::FromString(Context.AssetName));
CommandList->MapAction(FUICommandInfoDecl(CommandName, CommandLabel, CommandDescription, EUserInterfaceActionType::Button, FInputChord()), OpenAssetInViewerAction);
}
}
void RegisterAssetViewerCommands()
{
FLevelEditorModule& LevelEditorModule = FModuleManager::GetModuleChecked<FLevelEditorModule>("LevelEditor");
LevelEditorModule.OnContextMenuOpened().AddStatic(&OnContextMenuOpened);
}
#undef LOCTEXT_NAMESPACE
IMPLEMENT_MODULE(FDefaultModuleImpl, AssetViewerCommands)
```
这段代码监听上下文菜单打开事件,为每个选中的资源添加一个“在查看器中打开”的菜单项。如果资源已经在查看器中打开,则激活该查看器并将其置于前台。 如果资源尚未在查看器中打开,则打开一个新的查看器并将其置于前台。
阅读全文