keywords: [UE4]Switch Weapon at run-time (AttachToComponent), 运行时切换武器

Origin: SWeapon.cpp - EpicSurvivalGameSeries

void ASWeapon::AttachMeshToPawn(EInventorySlot Slot)
{
    if (MyPawn)
    {
        // Remove and hide
        DetachMeshFromPawn();

        USkeletalMeshComponent* PawnMesh = MyPawn->GetMesh();
        FName AttachPoint = MyPawn->GetInventoryAttachPoint(Slot);
        Mesh->SetHiddenInGame(false);
        Mesh->AttachToComponent(PawnMesh, FAttachmentTransformRules::SnapToTargetNotIncludingScale, AttachPoint);
    }
}

void ASWeapon::DetachMeshFromPawn()
{
    Mesh->DetachFromComponent(FDetachmentTransformRules::KeepWorldTransform);
    Mesh->SetHiddenInGame(true);
}

It’s better to use FAttachmentTransformRules::SnapToTargetNotIncludingScale when attaching, otherwise maybe there’s a big location offset between two actors when using KeepWorldTransform.

StaticMeshComponent无法附加到SkeletalMeshComponent上,附加后StaticMeshComponent会出现在场景中的随机位置,而不是父级SkeletalMeshComponent身上,且此时即使设置LocationOffset也无效。

通过NewObject<USkeletalMeshComponent>(Owner)运行时创建的SkeletalMeshComponent可以附加到父级SkeletalMeshComponent上,但是无法播放父级SkeletalMeshComponent的动画,即使设置了WeaponComp->SetMasterPoseComponent(PawnMesh)。建议在构造函数中创建后SkeletalMeshComponent,然后再run-time修改SkeletalMesh模型,run-time修改指定SkeletalMeshComponent的SkeletalMesh是没有问题的,且可以正常播放父级的动画。


念去去、千里烟波,暮霭沉沉楚天阔。----北宋·柳永《雨霖铃》