I am trying to change every Static Mesh Actor’s Material property.
I know I need to iterate over each Actor and find Static Mesh Component.
However, I can not modify Material properly.
Here is my code,
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);
}
}
Before:
After