UE4:C++动态添加UStaticMeshComponent

1. 构造函数内添加
xxActor::xxActor()
{
//tank mesh
static ConstructorHelpers::FObjectFinder TankStaticMesh(TEXT(“/Game/Meshs/TwinStick/TwinStickUFO.TwinStickUFO”));
TankMesh = CreateDefaultSubobject(TEXT(“TankMesh”));
TankMesh->SetStaticMesh(TankStaticMesh.Object);
TankMesh->SetCollisionProfileName(UCollisionProfile::Pawn_ProfileName);
RootComponent = TankMesh;
}

2. 构造函数外添加(一定要添加RegisterComponent(),否则不会显示!)
bool AItemActor::InitComponent(FVector loc, FRotator rot)
{
bool bRtn = false;
//mesh
m_pMeshComponent = (UStaticMeshComponent*)NewObject(this, TEXT(“Mesh”));
m_pStaticMesh = CreateStaticMesh(m_ItemType);
if (m_pMeshComponent && m_pStaticMesh)
{
m_pMeshComponent->SetStaticMesh(m_pStaticMesh);
m_pMeshComponent->SetCollisionProfileName(UCollisionProfile::Pawn_ProfileName);
m_pMeshComponent->SetRelativeRotation(rot);
m_pMeshComponent->SetRelativeLocation(loc);
m_pMeshComponent->RegisterComponent();
m_pMeshComponent->OnComponentHit.AddDynamic(this, &AItemActor::OnHit);

    RootComponent = m_pMeshComponent;
    bRtn = true;
}

return bRtn;

}

你可能感兴趣的:(UE4)