Detatch Actor Component

I’ve been at this for a couple hours now with no success.

I have a character with a SkeletalMesh component. When the character’s health reaches zero I’d like to turn their mesh into a ragdoll (this part is working) and the destroy the actor. The problem is that the mesh is part of the actor and is destroyed as well. I’ve tried 2 methods but I haven’t been able to get either one to work:

  1. Detatch the SkeletalMesh component and then destroy the character.
  2. Create a ASkeletalMeshActor, copy the character’s skeletalmesh component, spawn it, then destroy the character.

Any help would be greatly appreciated!

I am using C++.

This is in my humble experience so anyone else can jump in if I get something wrong:

The first method will not work as actor components without parents are automatically wiped by the garbage collector if left on their own.

The second method is closer to ideal but contains overhead (namely spawning the mesh).

My suggestion would be something in the middle of the two variants:

  1. Create a “container” actor and keep it alive at all times;
  2. Detach the SkeletalMesh component and immediately reattach it to the container;
  3. Turn it into a ragdoll;
  4. Then destroy the character.

You might want to keep the character if you do this frequently so you avoid destroying and spawning it all the time. Spawning and destroying actors is costly.

I think I’m really close to getting this to work properly… The mesh appears to successfully detach, but does NOT get attached to the newly spawned actor. Any help would be greatly appreciated.

AActor *character = GetOwner();

TArray<USkeletalMeshComponent*> children;

character->GetComponents<USkeletalMeshComponent>(children);

children[0]->DetachFromParent(true);

AActor* Ragdoll = GetWorld()->SpawnActor<AActor>(character->GetActorLocation(), FRotator::ZeroRotator);

children[0]->AttachToComponent(Ragdoll->GetRootComponent(), FAttachmentTransformRules::KeepWorldTransform);

Ragdoll ->GetMesh()->SetSimulatePhysics(true);

character->Destroy();