Atached演员网格不坚持父演员

时间:2019-03-09 20:06:22

标签: c++ visual-studio unreal-engine4

上下文:

我正在使用C ++在附加到Actor(Ship)的ActorComponent(ShieldComponent)中使用C ++创建。 当我移动飞船时,演员(盾牌)会留在世界上(不随飞船一起移动)。

重要的是什么:我在构造函数中未调用CreateShieldActor,因此无法使用ConstructorHelpers::FObjectFinder而不是StaticLoadObject/LoadObject来加载Mesh /材料。

我用于创建的C ++代码如下:

AShieldPart* UShieldComponent::CreateShieldActor(AActor* Owner, FString MeshName)
{
    //Create Shield Actor
    FVector Location = Owner->GetActorLocation();
    FRotator Rotator(0, 0, 0);
    FVector Scale(10, 10, 10);
    FActorSpawnParameters SpawnInfo;
    SpawnInfo.SpawnCollisionHandlingOverride = ESpawnActorCollisionHandlingMethod::AdjustIfPossibleButAlwaysSpawn;
    SpawnInfo.Owner = Owner;

    FTransform Transform(Rotator, Location, Scale);
    UClass * MeshClass = AShieldPart::StaticClass();

    AShieldPart* ShieldPart = GetWorld()->SpawnActor<AShieldPart>(MeshClass, Transform, SpawnInfo);

    //Attach Mesh to Shield Actor
    ShieldPart->AttachToActor(Owner, FAttachmentTransformRules(EAttachmentRule::KeepRelative, false));

    //Set Mesh for Shield
    ShieldPart->SetNewMesh(MeshName);

    //Set Material
    UMaterial* Material = Cast<UMaterial>(StaticLoadObject(UMaterial::StaticClass(), NULL, TEXT("/some/path")));
    ShieldPart->MeshComponent->SetMaterial(0, Material);

    return ShieldPart;
}


AShieldPart::AShieldPart()
{
    // Set this actor to call Tick() every frame.  You can turn this off to improve performance if you don't need it.
    PrimaryActorTick.bCanEverTick = true;

    RootComponent = CreateDefaultSubobject<USceneComponent>(TEXT("RootComponent"));
    SetRootComponent(RootComponent);

    MeshComponent = CreateDefaultSubobject<UStaticMeshComponent>(TEXT("MeshComponent"));
    MeshComponent->SetupAttachment(RootComponent);
}

void AShieldPart::SetNewMesh(FString MeshName)
{
    UStaticMesh* Mesh = Cast<UStaticMesh>(StaticLoadObject(UStaticMesh::StaticClass(), NULL, *MeshName));
    //UStaticMesh* Mesh = LoadObject<UStaticMesh>(nullptr, *MeshName);
    MeshComponent->SetStaticMesh(Mesh);
    MeshComponent->SetCollisionProfileName(TEXT("BlockAll"));
    MeshComponent->SetNotifyRigidBodyCollision(true);
    MeshComponent->SetSimulatePhysics(true);
    MeshComponent->SetEnableGravity(false);

    MeshComponent->RegisterComponent();
}

当我使用BP创建Actors(Shields)时,一切都很好...

enter image description here

1 个答案:

答案 0 :(得分:1)

该解决方案原来是将USceneComponent删除为RootElement。主元素必须为UStaticMeshComponent,然后它才能附加到父元素(Ship)。

AShieldPart::AShieldPart()
{
    // Set this actor to call Tick() every frame.  You can turn this off to improve performance if you don't need it.
    PrimaryActorTick.bCanEverTick = true;

    // Creating MeshComponent and attach to RootComponent
    MeshComponent = CreateDefaultSubobject<UStaticMeshComponent>(TEXT("MeshComponent"));
    RootComponent = MeshComponent;
    MeshComponent->AttachToComponent(RootComponent, FAttachmentTransformRules(EAttachmentRule::SnapToTarget, true));

    ...