1.dynamic create component
正常方法添加组件方法是
On Character.h I add a USpringArm and UChildActor component :
UPROPERTY(VisibleAnywhere, BlueprintReadOnly, Category = InventoryCamera)
TSubobjectPtr<class USpringArmComponent> InventorySpringArm;
UPROPERTY(VisibleAnywhere, BlueprintReadOnly, Category = InventoryCamera)
TSubobjectPtr<class UChildActorComponent> InventoryCamera;
On Character.cpp Constructor I add this code to Initialize those Actors :
InventorySpringArm = PCIP.CreateDefaultSubobject<USpringArmComponent>(this, TEXT("InventorySpringArm"));
InventorySpringArm->AttachTo(CapsuleComponent);
InventorySpringArm->bUseControllerViewRotation = false;
InventoryCamera = PCIP.CreateDefaultSubobject<UChildActorComponent>(this, TEXT("InventoryCamera"));
InventoryCamera->ChildActorClass = UCameraComponent::StaticClass();
InventoryCamera->CreateChildActor(); // <-- this code throws a Compile Error下面会说道childactor这么生成会有问题的
InventoryCamera->AttachTo(InventorySpringArm);
ps:也有的版本PCIP写成ObjectInitiallizer
但这个方法问题在于CreateDefaultSubobject 只能在构造函数里面调用
因此想要动态生成组件方法是:
Creating and Registering Components During Runtime
//in some AActor class void AYourActor::CreateComponent(UClass* CompClass,const FVector& Location, const FRotator& Rotation, const FName& AttachSocket=NAME_None) { FName YourObjectName("Hiiii"); //CompClass can be a BP UPrimitiveComponent* NewComp = ConstructObject<UPrimitiveComponent>( CompClass, this, YourObjectName); if(!NewComp) { return NULL; } //~~~~~~~~~~~~~ NewComp->RegisterComponent(); //You must ConstructObject with a valid Outer that has world, see above NewComp->SetWorldLocation(Location); NewComp->SetWorldRotation(Rotation); NewComp->AttachTo(GetRootComponent(),SocketName,EAttachLocation::KeepWorldPosition); //could use different than Root Comp
参考:
1.https://forums.unrealengine.com/showthread.php?52410-What-is-the-correct-way-to-create-and-add-components-at-runtime
2.ChildActorComponent的createChildActor方法使用,未解析外部引用
查看ChildActorComponent.h的源代码就知道
中间有
//start interface
......
//end interface
的注释,createChildActor方法在下面,并没有暴露出来
这里要使用childActorComponent->OnComponentCreated();方法
它会内部调用createChildActor方法
参考:
1.https://answers.unrealengine.com/questions/90283/unresolved-externals-error-with-uchildactorcompone.html
2.https://answers.unrealengine.com/questions/101002/uchildcomponentactor-createchildactor-compile-erro.html