UStaticMeshComponent Set Material At Runtime

The following code compiles but then causes unreal to crash with errors saying “File Not Found”
I’ve tried changing the string to the literal file location but get the same error. Can someone explain to me exactly what my string should be after ““DefaultMaterial(TEXT(”*******));”"
where the asterisks are.
My TestMat material is in my main content folder in the Engine Browser.
Thanks in advance.

static ConstructorHelpers::FObjectFinder DefaultMaterial(TEXT(“Material’/Game/Content/TestMat.TestMat’”));
if (DefaultMaterial.Object!=NULL)
{
//TheMaterial = (UMaterial*)Material.Object;
WActor->SetMaterial(0, DefaultMaterial.Object);
}

I recommand you to defined your Material in .h with UPROPERTY(EditAnywhere) and to set it in blueprint. It is the best way to maintain your code.

Where are you using this code ? the function static ConstructorHelpers::FObjectFindershoulb be call only in constructor.

So I need to be able to change the material at runtime, and I need to be able to select from a large array of materials (over 100), which is why I was hoping to do this in code rather than having a ridiculously large and borderline unusable blueprint.

I see that this is possible from this forum post

But he is only changing the color of the default material in this example, do you maybe know how to select the specific material using his method?

I think you have to use DynamicMaterial. I give you some code. The code Get all material of a Mesh. Create dynamic Material from it and then reapplied material on mesh. In the interval you can modify your material. I use it to set some Material parameter:

Mat->SetVectorParameterValue(*ParamName, NewParam);


//Create Dynamic Material for all material of a Mesh
for (auto indexMat = 0; indexMat < Mesh->GetNumMaterials(); indexMat++)
{
	UMaterialInterface *matToReplace = Mesh->GetMaterial(indexMat);
	if (matToReplace)
	{
		UMaterialInstanceDynamic* Mat = Mesh->CreateDynamicMaterialInstance(indexMat, matToReplace);
		if (Mat)
		{
			DynamicMaterials.Materials.Add(Mat);
 		}
	}
}


    //Set Material
for (auto indexMat = 0; indexMat < Mesh->GetNumMaterials(); indexMat++)
{
    UMaterialInterface *matToReplace = DynamicMaterials[Index].Materials[indexMat];
    if (matToReplace)
    {
    	Mesh->CreateAndSetMaterialInstanceDynamicFromMaterial(indexMat, matToReplace);
    }
}

I don’t know if i answer to your question but maybe it can help you.

The error message you got probably come from your material path but i don’t see error.

This is brilliant, thank you!