How to attach Actor to Character by c++

Hi.
I create torch as actor in character constructor and I would like attach this torch to hand of my character in c++ method. Hand of my character has socket.

TorchComponent = CreateDefaultSubobject<ATorchActor>(TEXT("TorchActor"));

and then I call another method to attach my torch to the hand.

TorchComponent->AttachToActor(this, FAttachmentTransformRules::KeepRelativeTransform, FName("hand_lSocket"));

I also try this:
TorchComponent->AttachToComponent(this->GetMesh(), FAttachmentTransformRules::KeepRelativeTransform, FName("hand_lSocket"));

Torch is invisible in both cases.
What can be a problem ?

1 Like

Actors are not meant to be used as subobjects and shouldn’t be created in constructors.

Spawn the actor on BeginPlay instead (or whenever you want the torch to appear).
Also you might want to use Snap attachment rather than relative.

//.h
    UPROPERTY()
    ATorchActor* MyTorch;

    virtual void BeginPlay() override;

//.cpp
void AMyCharacter::BeginPlay()
{
    Super::BeginPlay();

    MyTorch = GetWorld()->SpawnActor<ATorchActor>();
    MyTorch->AttachToActor(this, FAttachmentTransformRules::SnapToTarget, "hand_lSocket");
}
1 Like

I try your solution but It didn’t work properly. Torch was in the middle of character and my Following camera was affected too. Spawn method was right.

My solution :

TorchComponent = GetWorld()->SpawnActor<ATorchActor>(spawnParams);			
TorchComponent->TorchMesh->AttachToComponent(LubosTerezaMesh, FAttachmentTransformRules::KeepRelativeTransform, FName("hand_lSocket"));

This topic was automatically closed 30 days after the last reply. New replies are no longer allowed.