How can I create a material at runtime?

I am working on a custom importer, which will need to load geometry and materials at runtime. This will be similar to the fbx importer, but everything will happen at runtime. Right now I’m working on creating an array of materials and applying them to the faces. I’ve looked into the fbx importer, but it’s hard to find good documentation about what is happening. Does anyone have an idea about how this workflow would work?

For example, will I have to create an asset and then use a MaterialFactory? What would this look like?

Thanks!

Hi,

About dynamic material instances, you could start by creating a “template” material asset in the editor and, depending on what you need, expose two or more texture samples (for example diffuse & normal) that would be correctly linked in the material inputs.
Creating this template material would allow you to have better control on the end material used on your surfaces.

In your c++ code, you could create a UMaterialInstanceDynamic by using

UMaterialInstanceDynamic* UMaterialInstanceDynamic::Create(UMaterialInterface* ParentMaterial, UObject* InOuter)

where the ParentMaterial would be the loaded “template” material that you have created in the editor, and use

void UMaterialInstanceDynamic::SetTextureParameterValue(FName ParameterName, UTexture* Value)

with your diffuse/normal parameter name as first parameter, and the loaded imported texture as second.

Depending on the materials you would like to import, you would just have to update the template material in the editor, exposing every parameters that make sense to your specific implementation, and update them in your c++ code.

The UMaterialInstanceDynamic, in this case, would just be used to update the exposed parameters, while the computation of the surface rendering would be done on the editor side.

Hope this helps for the material part,
cheers.

Thanks for the response! This is helpful and definitely could be a solution. I’ll give it a try! However, I’m going to keep looking into fully creating the material at runtime, in order to do as little as possible in the editor. If possible, this would be the ideal solution.