How do I use the SetMaterial function?

I am new to unreal, and I want to use the SetMaterial function on a UProceduralMeshComponent, but I can’t find anything that says how to actually use it. I have a material in the Content folder. Could someone tell me how to apply that material to my UProceduralMeshComponent using set material? Thanks.

Example code of setting a material. In this case its a ghost effect when something is selected.

// .h file
* The material instance of the ghosting material, used when the item is selected in inventory
UMaterialInterface* _ghostMaterial = nullptr;

// in constructor in .cpp file
// init ghost material
FString ghostMaterialName = "/Game/Materials/WorldEffects/GhostEffect.GhostEffect";
static ConstructorHelpers::FObjectFinder<UMaterialInterface> ghostMaterialAsset(*ghostMaterialName);
_ghostMaterial = ghostMaterialAsset.Object;

// in .cpp file function to set material for each material index in the mesh
// set all mesh materials to ghost material
USkeletalMeshComponent* mesh = GetMesh();
if (mesh)
  int numberOfMaterials = mesh->GetNumMaterials();
  for (int index = 0; index < numberOfMaterials; index++)
    if (mesh->GetMaterial(index))
      mesh->SetMaterial(index, _ghostMaterial);


Just in case it is or isn’t clear, **Shmoopy1701 **method is a hardcoded file path using an object constructor. You can do it this way, but then you can never move the item out of that folder, you would have to update all of your code if you did and recompile of course.

The other way to do is is to create a blueprint data class of your c++ class that is going to set this material. Then open up the blueprint and then you can set the material id as a drop down in the blueprint editor. So moving it wont matter, the serialization will detect this and update accordingly.

You would need to change

UPROPERTY(VisibleInstanceOnly) UMaterialInterface* _ghostMaterial = nullptr;


UPROPERTY(EditDefaultsOnly) UMaterialInterface* _ghostMaterial = nullptr; //Or EditAnywhere

the code would be the same, but you’d get rid of the constructor helper entirely. It’s also recommeneded you to a check for _ghostMaterial to make sure its not null when you call setmaterial.