Can't assign material instance to UStaticMesh

I’m trying to programmatically assign a material instance to a UStaticMesh.



UStaticMesh* staticMesh = LoadObject<UStaticMesh>(nullptr, TEXT("/Game/testMesh"));
UMaterialInstanceDynamic* mInstance = LoadObject<UMaterialInstanceDynamic>(nullptr, TEXT("/Game/testMaterial"));
FName materialName = "testMaterial";
UStaticMeshComponent* meshComponent = NewObject<UStaticMeshComponent>();

meshComponent->SetStaticMesh(staticMesh);
meshComponent->SetMaterialByName(materialName, mInstance);


When I run this, it just leaves the default material (WorldGridMaterial) assigned to each slot. I’ve checked that the staticmesh and material instance load in properly, but it still doesn’t work. Any advice?

Are you sure the material slot name is correct?

Maybe try using SetMaterial to set the material by index and see if it works.

https://docs.unrealengine.com/en-US/…ial/index.html

Also, FName’s are created using:



FName materialName = FName(TEXT("testMaterial"));


https://docs.unrealengine.com/en-US/…ame/index.html

You should also pay attention to the Unreal coding standard for variable naming

materialName should be MaterialName. Title case not camel case.