Download

Attaching an Actor on an Skeletal Mesh Socket

Hi everyone !
As a beginner on Unreal Engine, I have many issues with attaching an actor (which is basically a weapon) to the hand of my Character !
Here is where I tried to attach the weapon to the socket



AHumanoide::AHumanoide()
{
    FName fnWeaponSocket = TEXT("hand_lSocket");
    UWorld* World = GetWorld();
    if (World)
    {
        arc=GetWorld()->SpawnActor<AArmeADistance>(AArmeADistance::StaticClass());
        arc->AttachRootComponentTo(GetMesh(), fnWeaponSocket, EAttachLocation::SnapToTarget, true);
    }
}

And here is the constructor of my weapon


AArmeADistance::AArmeADistance()
{
    RootComponent = CreateDefaultSubobject<USceneComponent>(TEXT("RootComponent"));
    //définition du mesh
    StaticMeshComponent = CreateDefaultSubobject<UStaticMeshComponent>(TEXT("Mesh"));
    static ConstructorHelpers::FObjectFinder<UStaticMesh> mesh(TEXT("StaticMesh'/Game/Projet_Dragonnier/Equipement/Armes/ADistance/Arc/Arc.Arc'"));
    StaticMeshComponent->SetStaticMesh(mesh.Object);
    StaticMeshComponent->SetSimulatePhysics(false);
    StaticMeshComponent->SetCollisionEnabled(ECollisionEnabled::NoCollision);
    StaticMeshComponent->SetupAttachment(RootComponent);
}

I’ve tried many things but the weapon is still spawning at the origin and never in the hand off my character …
Could someone help me ? :frowning:
Thanks you a lot !

If you are using character, shouldn’t you use SkeletalMesh, instead of StaticMesh?

AArmeADistance is the class for the Weapon, which is an actor, so I think using a StaticMesh is correct no ?
In the class AHumanoide, which extends ACharacter, the Mesh is indeed a SkeletalMesh (that I get with GetMesh()) :wink:

yep, sorry my bad.

Found the problem !
The best way to do what I wanted to do is to spawn and attach the actor in the BeginPlay() method :


void AHumanoide::BeginPlay()
{
    Super::BeginPlay();
    FName fnWeaponSocket = TEXT("hand_lSocket");
    FTransform socketTransform = GetMesh()->GetSocketTransform(fnWeaponSocket, ERelativeTransformSpace::RTS_World);
    FActorSpawnParameters parametres;
    parametres.SpawnCollisionHandlingOverride = ESpawnActorCollisionHandlingMethod::Undefined;
    ArmeADistance = GetWorld()->SpawnActor<AArmeADistance>(AArmeADistance::StaticClass(), socketTransform);
    if (ArmeADistance)
    {
        ArmeADistance->AttachToComponent(GetMesh(), FAttachmentTransformRules(EAttachmentRule::SnapToTarget, true), fnWeaponSocket);
    }

}

It is now perfectly working, hope it will help another beginner like me in the future ! :wink: