Creating material with texture in c++ at runtime

I need to load a skeletal mesh at runtime.
My code is based on the ACharacter class and creates a skeletal mesh in the constructor from a custom model format.
The mesh has N materials, each with at least a diffuse texture.
I can create materials and load textures (UTexture2D) at runtime without problems.
My problem is to assign the texture to the material.
In the editor I end up with a skeletal mesh and all the materials, but no textures assigned to them.

What is the best method to do that? Or at least a working one?

PS : I heard that assigning a texture is done in PostLoad or on the components post-init, but these methods aren’t called in the editor. I need the solution to work both for the editor and ingame.

The easiest way to do this is with Material Instances.

Create a UMaterial with a Texture Parameter to serve as the base material. At runtime, create a UMaterialInstanceDynamic and call SetTextureParameterValue to provide a value to your parameter.

If you set your base UMaterial as the material for the mesh section, you can even use the convenience method UPrimitiveComponent::CreateAndSetMaterialInstanceDynamic to create the MID.

Thanks, I’ll look into that. So far I don’t know when CreateAndSetMaterialInstanceDynamic is called, but it may suit me.
By the way would you know how to debug a “FRenderResource was deleted without being released first!” fatal error?

I don’t know what the issue with FRenderResource is. I would start by looking at the stack trace to find which subclass of FRenderResource is throwing the error, and ideally attach a debugger. I suspect that you have a mistake in how you’re creating the skeletal mesh, and you forgot to call InitResources after you construct it.