How to change material for a mesh in cpp?

Hi guys,

Let’s say I have the reference of a material in the editor [via right click, copy reference]. And I have a static mesh.
Using the function SetMaterial() of the static mesh component, the function takes a UMaterialInterface pointer type as a parameter.
How can I use the material reference copied from the editor and change the mesh’s material? I didn’t find an immediate set material function in UMaterialInterface, and I am not familiar with materials in cpp at all.

The way I generally do it is: declare the material in .h (this is in case you create blueprints based on the cpp class:

UPROPERTY(EditAnywhere)
UMaterialInterface* MaterialRef;

Set the reference in the blueprint, and then you can use it in your cpp.

1 Like

A better approach it to be able to set the material in your Blueprint, rather than have a hardcoded path.

.h

UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = MyBP)
		UMaterialInterface* MyMaterial;

.cpp

if(MyMaterial){
 MyStaticMesh->SetMaterial(0, MyMaterial);
}
1 Like

Thanks, this is useful.