Cannot attach actor to socket C++ UE5

I have a Blueprint Actor that I am attempting to attach to my C++ Pawn’s hand socket.

I did a quick attachment using Blueprints to understand the process and everything worked well.

Looking at the Blueprint code (copy/paste), I learned that I need the K2_AttachToComponent function. But when trying that with the following, the attachment doesn’t seem to work in the editor despite the return boolean showing true.


    // My character that will hold the weapon
	skeletalMesh = CreateDefaultSubobject<USkeletalMeshComponent>(TEXT("Hero_USkeletalMeshComponent"));
   USkeletalMesh* meshToUse = Cast<USkeletalMesh>(StaticLoadObject(USkeletalMesh::StaticClass(), NULL, TEXT("/Game/Core/SM_Hero")));
	if (meshToUse && skeletalMesh)
	{
		skeletalMesh->SetSkeletalMesh(meshToUse);
    }
   
    // The hand socket of my character
	USkeletalMeshSocket* staffSocket = (USkeletalMeshSocket*) skeletalMesh->GetSocketByName("RightHandStaffSocket");
	if (staffSocket) {
		GEngine->AddOnScreenDebugMessage(-1, 15.0f, FColor::Yellow, staffSocket->SocketName.ToString());
	}

	const FTransform handTransform = skeletalMesh->GetSocketTransform(FName("RightHandStaffSocket"), ERelativeTransformSpace::RTS_ParentBoneSpace);
	const ConstructorHelpers::FObjectFinder<UBlueprint> StaffBP(TEXT("Blueprint'/Game/Core/BP_Staff'"));
	if (StaffBP.Object) {
        // The staff to be attached to my character
		AActor* NewActor = GetWorld()->SpawnActor(StaffBP.Object->GeneratedClass, &handTransform);
		NewActor->SetActorEnableCollision(false);

      // 1st method) This just crashes the editor
      // and stangely requires me to completely undo code before the editor chills out again (I cannot just commend it out)
		staffSocket->AttachActor(NewActor, skeletalMesh);

      // 2nd method) This is successful but does not attach the weapon to the character, it is just floating in space
		bool attachResult = NewActor->AttachToComponent(skeletalMesh, FAttachmentTransformRules::SnapToTargetNotIncludingScale, TEXT("RightHandStaffSocket"));
		GEngine->AddOnScreenDebugMessage(-1, 15.0f, FColor::Yellow, FString::Printf(TEXT("attachResult! %s"), attachResult ? TEXT("true") : TEXT("false")));

      // 3rd method) This is also successful but does not attach the weapon to the character, it is just floating in space
		attachResult = NewActor->K2_AttachToComponent(skeletalMesh, TEXT("RightHandStaffSocket"), EAttachmentRule::SnapToTarget, EAttachmentRule::SnapToTarget, EAttachmentRule::SnapToTarget, true);
		GEngine->AddOnScreenDebugMessage(-1, 15.0f, FColor::Yellow, FString::Printf(TEXT("attachResult! %s"), attachResult ? TEXT("true") : TEXT("false")));
	}

Above are three different methods I’ve tried to getting this to work, and all either do not work or crash the editor.

Any ideas or tips? Most posts with similar issues either have outdated solutions or solutions that don’t seem to work at all.

Thanks!