I currently have a static mesh component with a default material. How would I go about changing the material dynamically with c++ code? I’ve tried using the SetMaterial function belonging to the static mesh component though that doesn’t change anything. Any alternate approaches/ explanation of how this works?
Thanks.
I recently went through this too. My end result, which does work, was to use a TArray Materials in my Pawn class, and when spawning the pawn assign a random material to it from the array:
//
// located in pawn header file and assigned in Blueprint editor
.h
UPROPERTY(EditAnywhere)
TArray<UMaterialInterface*> Materials;
//
// located in pawn manager responsible for spawning them
.h
TSubclassOf<class AMyPawn> PawnClass;
.cpp
FVector spawnLocation = FVector(0.0f, 0.0f, 0.0f);
FRotator spawnRotation = FRotator::ZeroRotator;
AMyPawn* pawn = GetWorld()->SpawnActor<AMyPawn>(PawnClass, spawnLocation, spawnRotation);
if (pawn != nullptr)
{
AMyPawn* defaultPawn = PawnClass.GetDefaultObject();
int32 materialCount = defaultPawn->Materials.Num();
int m = FMath::RandRange(0, materialCount - 1);
const TArray<UActorComponent*>& theComponents = pawn->GetComponents();
int32 componentCount = theComponents.Num();
for (int32 x = 0; x < componentCount; x++)
{
USkeletalMeshComponent* mesh = Cast<USkeletalMeshComponent>(theComponents[x]);
if (mesh != nullptr)
{
mesh->SetMaterial(0, defaultPawn->Materials[m]);
}
}
Of course for your needs you should be able to convert the USkeletalMeshComponent to UStaticMeshComponent (at least I think).