The component is not attached to the socket via C++ code

The component is not attached to the socket via C++ code.

my header code:
UPROPERTY(EditAnywhere)
	UBoxComponent* RHCollision;
my cpp code:
RHCollision = CreateDefaultSubobject<UBoxComponent>(TEXT("RHCollision"));
RHCollision->SetupAttachment(GetMesh(), TEXT("RightHand"));
1 Like

In my experience, attaching to sockets never really properly worked in the constructor for some reason.
Try setting up attachment in either OnConstruction() or BeginPlay() instead.

2 Likes

Have you compiled the code with the editor closed?

1 Like

Yes

I’m not sure about the solution, but I took a look into documentation

image
Have you tried with a Name variable instead of a TEXT one?

Something like:

FName RightHand = "RightHand"

RHCollision = CreateDefaultSubobject<UBoxComponent>(TEXT("RHCollision"));
RHCollision->SetupAttachment(GetMesh(), RightHand );
2 Likes

I’m looking at the syntax I’ve used in my project and it’s FName(ā€œsocketnameā€)

Try using that instead of TEXT(ā€œsocketnameā€)

1 Like

does not work(

does not work

Use AttachToComponent instead of SetupAttachment

1 Like

does not work(

const FAttachmentTransformRules AttachmentTransformRules(EAttachmentRule::KeepRelative, false);

RHCollision->AttachToComponent(GetMesh(), AttachmentTransformRules, FName("RightHand"));

Also verify that the socket exists, usually the syntax is more like ā€œRightHand_Socketā€

1 Like

I got a few questions about your code.

  1. How do you know if it’s not attached? Remember that sometimes properties declared in C++ are not visible in Blueprints.
    Try to change your UPROPERTY(EditAnywhere) to UPROPERTY(EditAnywhere, BlueprintReadWrite) to visualize it on editor.

  2. Are you sure ā€œGetMesh()ā€ is initialized by the time you set up attachments to it?
    May be something to confirm.

1 Like

the component is attached to the mesh, but not attached to the socket

The socket name is a suspect, the autogenerated ones are like ā€œbonename_##socketā€

Check the socket name or if it even exists on the skeleton of your skeletal mesh asset

1 Like

Such a socket exists. I created it myself

Ah, yeah.

I used SetRelativeLocation to adjust the component position before using AttachToComponent.
For me that worked better than snapping.

You can either use SnapToTarget AttachmentTransformRule if it works for you as is, or use SetRelativeLocation to first adjust the position of the component to attach on spawn and then use the keep relative attachmenttransformrule.

1 Like

I found a solution. In fact, the object is attached to the socket, it’s just not displayed)

1 Like

It works. Set it up as this, and it is exactly where it should be and doing exactly what I’d expect. Thanks for the tip.

WeaponCollider = CreateDefaultSubobject<UBoxComponent>(TEXT("WeaponCollider"));
WeaponCollider->SetupAttachment(GetMesh(), FName("Collision_Sword"));
1 Like