Download

What is the correct way to add Child Actors at runtime?

I understand how to add components to another class in the constructor using CreateDefaultSubobject. However, I’ve heard this only works in the constructor. What is the correct way to do this so that it works in both the constructor and at runtime?
I need to be able to add and delete components at will during runtime.
I’ve been searching for all sorts of things and not coming up with a clear answer…

UStaticMeshComponent *MyComponent = NewObject<UStaticMeshComponent>(this, UStaticMeshComponent::StaticClass());
MyComponent->RegisterComponent();

if the this parameter doesn’t work, then put GetTransientPackage().

To delete, its MyComponent->UnregisterComponent();

This is how I do it, but I do it at construction-time and it needs to never fail regardless of its churn, so I’m a little over-safe:


//----------------------------------------------------------------------------------------------------
bool AMech::SetupPart( UChildActorComponent** MechPartChildActor, FName MechPartName, TSubclassOf< AActor > ChildClass )
{
// Setup a mech part (as part of ::CreateDefaultSubobjects -- just consolidating logic in one place).
*MechPartChildActor = CreateDefaultSubobject< UChildActorComponent >( MechPartName, true );
( *MechPartChildActor )->SetupAttachment( RootComponent );
( *MechPartChildActor )->SetRelativeLocation( FVector::ZeroVector, false, nullptr, ETeleportType::TeleportPhysics );
( *MechPartChildActor )->SetRelativeRotation( FRotator::ZeroRotator, false, nullptr, ETeleportType::TeleportPhysics );

// Set the child actor class.
( *MechPartChildActor )->SetChildActorClass( ChildClass );

return true;
}

… later to get the actual child actor …]


// Locomotion.
MechPart_Locomotion = Cast< AMechPartLocomotion >( Locomotion->GetChildActor( ) );
if( !IsValid( MechPart_Locomotion ) )
{
// Create the child actor and set the local (transient) actor pointer.
Locomotion->CreateChildActor( );
MechPart_Locomotion = Cast< AMechPartLocomotion >( Locomotion->GetChildActor( ) );
}
MechPart_Locomotion->Mech = this;

Awesome, thanks so much guys!