UE5 编辑器下添加组件

定义一个CallInEditor的函数:

cpp 复制代码
UFUNCTION(BlueprintCallable, CallInEditor)
void AddGenerateComponent();

直接AddComponent,会在移动后消失,且反射没法找到生成的组件。这里需要用到USubobjectDataSubsystem,需要在Build.cs内部添加模块:SubobjectDataInterface,代码如下:

cpp 复制代码
void AAEGenerator::AddGenerateComponent()
{
	if (USubobjectDataSubsystem* Subsystem = Cast<USubobjectDataSubsystem>(GEngine->GetEngineSubsystemBase(USubobjectDataSubsystem::StaticClass())))
	{
		TArray<FSubobjectDataHandle> OutArray;
		Subsystem->GatherSubobjectData(this, OutArray);
		if (OutArray.Num() > 0)
		{
			FAddNewSubobjectParams Params;
			Params.ParentHandle = OutArray[0];
			Params.NewClass = UGeneratorComponent::StaticClass();
			FText FailedReason;
			FSubobjectDataHandle Handle = Subsystem->AddNewSubobject(Params, FailedReason);
			if (Handle.GetData())
			{
				if (UGeneratorComponent* GeneratorComponent = const_cast<UGeneratorComponent*>(Cast<UGeneratorComponent>(Handle.GetData()->GetObject())))
				{
					GeneratorComponent->AttachToComponent(Root, FAttachmentTransformRules::KeepRelativeTransform, NAME_None);
					GeneratorComponent->SetRelativeTransform(FTransform::Identity);
					GeneratorComponent->RegisterComponent();
				}	
			}
		}
	}
}
相关推荐
暮志未晚Webgl2 小时前
UE5使用CommonUI实现手柄进行UI导航
ui·ue5·commonui
zhensherlock2 小时前
Protocol Launcher 系列:一键唤起 VSCodium 智能 IDE
javascript·ide·vscode·typescript·开源·编辑器·github
i学长的猫3 小时前
PM2 管理 Cloudflared 隧道 Neo-mac 及后台运行
linux·编辑器·vim
lanhuazui103 小时前
vscode打不开终端窗口
ide·vscode·编辑器
低保和光头哪个先来3 小时前
TinyEditor 篇3:拖拽图片到编辑器并同步上传至服务器
运维·服务器·编辑器
fengjay013 小时前
AI Coding——VsCode
ide·vscode·编辑器
海天一色y4 小时前
Vim 编程完全指南:从入门到精通
编辑器·vim·excel
zhangzhangkeji5 小时前
(18)UE5 接口里的两个宏 GENERATED_UINTERFACE_BODY() 与 GENERATED_IINTERFACE_BODY()
ue5
R-sz5 小时前
虚幻 UE5 像素流多用户部署,像素流多实例部署
ue5·游戏引擎·虚幻