My question is how can make a parent / child relationship for actors in C++? So far I’ve tried getting the root components of both objects and then using the AttachTo method, but it does not behave as expected. The SectorVolume and Prop are both derived from the Actor class.
Here is an example of what I want to do:
at 11:30 in the video the developer adds the door handles as children to the SlidingDoor Actor in the Scene Outliner.
I’d like to do this in C++.
// code
#include “AdvVehicleTemplate.h”
#include “SectorVolume.h”
#include “Components/TextRenderComponent.h”
#include “Prop.h”
// Sets default values
ASectorVolume::ASectorVolume(const FObjectInitializer& ObjectInitializer)
{
// Set this actor to call Tick() every frame. You can turn this off to improve performance if you don’t need it.
PrimaryActorTick.bCanEverTick = false;
// Create the simple StaticMeshComponent to represent the sector area
Sector = ObjectInitializer.CreateDefaultSubobject<UBoxComponent>(this, TEXT("Sector"));
Sector->bGenerateOverlapEvents = true;
// Set the StaticMeshComponent as the root component
RootComponent = Sector;
// Set the prop count range with defaults
MinPropCount = 25.f;
MaxPropCount = 50.f;
// Set the rotation ranges with defaults
MinRotX = 0.f;
MinRotY = 0.f;
MinRotZ = -45.f;
MaxRotX = 0.f;
MaxRotY = 0.f;
MaxRotZ = 45.f;
}
// Spawn the prop
void ASectorVolume::SpawnProp()
{
// Check for a Valid World
UWorld* const World = GetWorld();
if (World)
{
// Set the spawn parameters
FActorSpawnParameters SpawnParams;
SpawnParams.Owner = this;
SpawnParams.Instigator = Instigator;
// Get a random location to spawn the prop
FVector SpawnLocation = GetRandomPointInVolume();
// Get a random rotation for the prop
FRotator SpawnRotation;
SpawnRotation.Yaw = FMath::FRandRange(MinRotX, MaxRotX);
SpawnRotation.Pitch = FMath::FRandRange(MinRotY, MaxRotY);
SpawnRotation.Roll = FMath::FRandRange(MinRotZ, MaxRotZ);
// spawn the prop
AProp* const SpawnedProp = World->SpawnActor<AProp>(Prop, SpawnLocation, SpawnRotation, SpawnParams);
// When the sector’s transform moves, I would like the SpawnedProp to move with it
USceneComponent* tempComponent = this->GetRootComponent();
if (tempComponent != nullptr)
{
USceneComponent* SpawnedRoot = SpawnedProp->GetRootComponent();
if (SpawnedRoot != nullptr)
{
SpawnedRoot->AttachTo(tempComponent);
DebugDisplayString = FText::FromString(tempComponent->GetName()); // displays "Sector" which is the static mesh from above
}
}
else
{
DebugDisplayString = FText::FromString("No parent component");
}
}
}