Applying material to multiple meshes in c++

Hello.

I’m creating an actor, which has 256 meshes. Every mesh uses the same material, given as ‘uproperty’. Is there any fast, efficient method to apply the material to all the meshes at once?

Create a material instance of your uproperty material then loop over your meshes and SetMaterial(index, pMaterialInstance); What kind of mesh is it ? Static ? Skeletal ? Do you use a UStaticMeshComponent for each ?

I’m using UStaticMeshComponent, and it’s static mesh. What is the ‘index’ argument?

You’re talking about an efficient way to do it but we are talking about assignation so you’re forced to go over every mesh and assign them your material. The only thing I could recommend is basic c++ tricks like using a contiguous memory container (TArray, vector) to prevent cash misses, but even here, you’re meshes are pointers so at every iteration your system have to look into the heap. Just do:
UMaterialInstanceDynamic* const pDynMat = UMaterialInstanceDynamic::Create(m_MyMaterial, this);
for(UStaticMeshComponent* pComponent : m_MyStaticMeshComps)
{
pComponent->SetMaterial(0, pDynMat );
}

Sorry about code format

I hoped there is a single function for that or so. Gonna go like that.
Thanks

void AYourActorWithTonsOfMesh::PostInitializeComponents()
{
Super::PostInitializeComponents();
UMaterialInstanceDynamic* const pDynMat = UMaterialInstanceDynamic::Create(m_MyMaterial, this);
for (UStaticMeshComponent* pComponent : m_MyStaticMeshComps)
{
pComponent->SetMaterial(0, pDynMat);
}
}