我正在尝试更改每个静态网格物体 Actor 的 Material 属性。我知道我需要迭代每个 Actor 并找到静态网格体组件。但是,我无法正确修改 Material 。
这是我的代码,
GEngine->AddOnScreenDebugMessage(-1, 5.f, FColor::Red, TEXT("START Modeling()"));
//Find Actor and change Material
UWorld* world = GetWorld();
//Material Path
FString matPath = "Material'/Game/StarterContent/Materials/M_Metal_Gold.M_Metal_Gold'";
//Material Instance
UMaterialInstanceConstant* material = Cast<UMaterialInstanceConstant>(StaticLoadObject(UMaterialInstanceConstant::StaticClass(), nullptr, *(matPath)));
//Iterate Every Static Mesh Actor
for (TActorIterator<AStaticMeshActor> ActorItr(world); ActorItr; ++ActorItr)
{
AStaticMeshActor *Mesh = *ActorItr;
//Just for Degbuging Purpose
GEngine->AddOnScreenDebugMessage(-1, 5.f, FColor::Red, FString::Printf(TEXT("Actor: %s"), *(ActorItr->GetName())));
GEngine->AddOnScreenDebugMessage(-1, 5.f, FColor::Red, FString::Printf(TEXT("Location: %s"), *(ActorItr->GetActorLocation().ToString())));
//Get Static Mesh Component
TArray<UStaticMeshComponent*> MaterialComps;
Mesh->GetComponents(MaterialComps);
//I get this code from community answer. I do not know how it works.
for (int32 Index = 0; Index != MaterialComps.Num(); ++Index)
{
UStaticMeshComponent* targetComp = MaterialComps[Index];
int32 mCnt = targetComp->GetNumMaterials();
for (int i = 0; i < mCnt; i++)
//This is the core code which actually changing material.
targetComp->SetMaterial(0, material);
}
}
我之所以想到这一点,是因为我正在通过迭代来改变每个 Actor 。
然而,它只会改变地板 Actor 的 Material 。
最佳答案
您仅更改索引为 0 的 Material 。
将targetComp->SetMaterial(0,material);
更改为targetComp->SetMaterial(i,material);
。它应该可以解决您的问题。
关于c++ - Unreal Engine 4 C++ 更改 AStaticMeshActor 的 StaticMeshComponent,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37960045/