写一个UE5.1 C++ 插件的例子
时间: 2024-02-05 11:12:53 浏览: 131
以下是一个简单的UE5.1 C++插件示例,它创建了一个新的Actor类并将其添加到编辑器的菜单中:
首先,创建一个新的UE5.1插件项目,选择“C++类”模板,并选择“插件”类别。
接下来,添加一个新的Actor类(例如,MyActor):
```cpp
// MyActor.h
#pragma once
#include "CoreMinimal.h"
#include "GameFramework/Actor.h"
#include "MyActor.generated.h"
UCLASS()
class MYPLUGIN_API AMyActor : public AActor
{
GENERATED_BODY()
public:
AMyActor();
protected:
virtual void BeginPlay() override;
public:
virtual void Tick(float DeltaTime) override;
};
```
```cpp
// MyActor.cpp
#include "MyActor.h"
AMyActor::AMyActor()
{
PrimaryActorTick.bCanEverTick = true;
}
void AMyActor::BeginPlay()
{
Super::BeginPlay();
}
void AMyActor::Tick(float DeltaTime)
{
Super::Tick(DeltaTime);
}
```
接下来,创建一个新的菜单项并添加一个新的Actor:
```cpp
// MyPlugin.cpp
#include "MyPlugin.h"
#include "MyActor.h"
#define LOCTEXT_NAMESPACE "FMyPluginModule"
void FMyPluginModule::StartupModule()
{
// 创建菜单项
FLevelEditorModule& LevelEditorModule = FModuleManager::LoadModuleChecked<FLevelEditorModule>("LevelEditor");
LevelEditorModule.GetMenuExtensibilityManager()->AddExtender(
MakeShared<FExtender>()
->AddMenuExtension(
"Actor",
EExtensionHook::After,
nullptr,
FMenuExtensionDelegate::CreateLambda([](FMenuBuilder& MenuBuilder) {
MenuBuilder.AddMenuEntry(
LOCTEXT("MyPlugin", "Add My Actor"),
LOCTEXT("MyPluginTooltip", "Adds a new MyActor to the level"),
FSlateIcon(),
FUIAction(FExecuteAction::CreateLambda([]() {
// 创建新的Actor并将其添加到场景中
UWorld* World = GEditor->GetEditorWorldContext().World();
if (World)
{
FActorSpawnParameters SpawnParams;
SpawnParams.Owner = GEditor->GetEditorWorldContext().World()->GetFirstPlayerController();
World->SpawnActor<AMyActor>(AMyActor::StaticClass(), FVector::ZeroVector, FRotator::ZeroRotator, SpawnParams);
}
}))
);
})
)
);
}
void FMyPluginModule::ShutdownModule()
{
// 移除菜单项
if (FModuleManager::Get().IsModuleLoaded("LevelEditor"))
{
FLevelEditorModule& LevelEditorModule = FModuleManager::GetModuleChecked<FLevelEditorModule>("LevelEditor");
LevelEditorModule.GetMenuExtensibilityManager()->RemoveExtender(MenuExtender);
}
}
#undef LOCTEXT_NAMESPACE
IMPLEMENT_MODULE(FMyPluginModule, MyPlugin)
```
最后,在插件的.build.cs文件中添加对Engine和LevelEditor模块的依赖:
```cpp
// MyPlugin.build.cs
using UnrealBuildTool;
public class MyPlugin : ModuleRules
{
public MyPlugin(ReadOnlyTargetRules Target) : base(Target)
{
PCHUsage = PCHUsageMode.UseExplicitOrSharedPCHs;
PublicDependencyModuleNames.AddRange(new string[] { "Core", "CoreUObject", "Engine", "InputCore" });
PrivateDependencyModuleNames.AddRange(new string[] { "LevelEditor" });
}
}
```
现在,在编辑器的Actor菜单中,您应该会看到一个新的“Add My Actor”菜单项,它将添加一个名为MyActor的新Actor到场景中。
阅读全文