Editor:How do I assign a material to the Materials array of a UStaticMesh

I’d like to be able to do some editor-side setup of materials – in particular creating and applying material instances from a known set of material archetypes – in an editor plugin. The goal is to make it easier for artists to assign instances from a list of approved materials: select the static mesh in the content browser, push an editor button, and all of its default materials will be assigned instances based on some project-specific logic.

While I can get a UStaticMesh and I can inspect the materials that it currently references, the .Materials property on the `UStaticMesh instance is private so I can’t set it. What’s the correct set of operations to change the default material assignments a static mesh asset and then save those changes to the asset ?

Hey Undead Steve-

The mesh itself it not responsible for setting the material, this is done by the static mesh component through the inherited UMeshComponent::SetMaterial() function. For example, if you declare a UStaticMeshComponent* MyMeshComp; Then you can use MyMeshComp->SetMaterial(MaterialRefernce); to assign the material to the mesh that is assigned to that component.

Cheers

I’m not trying to assign to a scene actor; i’m trying to update a static mesh asset. Do I get a UStaticMeshComponent when I’m loading an asset using an FAssetData in the editor? I’ve gotten it to work more or less like this:

   TArray<FAssetData> SelectedAssets;
ContentBrowserModule.Get().GetSelectedAssets(SelectedAssets);
for (auto Selected: SelectedAssets)
{
	auto *asset = Selected.GetAsset();
	UStaticMesh *test = Cast<UStaticMesh>(asset);
	test->Materials[0] = myMaterial;
	test->MarkPackageDirty();
}

Is that not safe?

Reading that code as is without testing it looks like it should work for what you’re doing. If it is indeed working for you then I would continue using it.