How can I get a reference to a Material with C++?

Hey Guys,

I suppose this is in fact a pretty simple question but I just cant figure out how to do it:
I created two materials and I want to assign them to a mesh that I created, but I don’t know how to get a reference to the materials. The method to set the material requires a UMaterialInterface. Maybe it has to do something with the “Copy Reference”-option in the menu you get when you right-click a material?

Thanks in advance,

Already been asked before:

have yout tried this one?

Thanks for your reply, but I already found both threads and they aren’t helping me, as the problem there is different. They are trying to get a material from a mesh that is already assigned to it and I want to assign a material to a mesh, whereas the material only “exists” in the UE-Editor in the Blueprints-Section and I dont’t know how to create a reference to it, so that I can assign the material to my mesh. So basically I’m creating the mesh at runtime and I don’t know which of the materials I will assign beforehand, therefore I need a possibility to access the materials.
Sorry if that wasn’t clear from my first post.

Awesome! Thank you! That’s exactly what I searched for.
I don’t know how I couldn’t find that thread as it is exactly what I needed…

Happens to the best :wink:

This can only be used insider UObject constructor. What if one want to load material somewhere else
?

From Trying to load Material with absolute path - #2 by adludum

template <typename ObjClass>
static FORCEINLINE ObjClass* LoadObjFromPath(const FName& Path)
{
	if (Path == NAME_None) return nullptr;

	return Cast<ObjClass>(StaticLoadObject(ObjClass::StaticClass(), nullptr, *Path.ToString()));
}

static FORCEINLINE UMaterial* LoadMaterialFromPath(const FName& Path)
{
	if (Path == NAME_None) return nullptr;

	return LoadObjFromPath<UMaterial>(Path);
}

Then load the UMaterial:

static const TCHAR* MaterialPath = TEXT("/Path/Of/M_Mat.M_Mat");
UMaterial* Material = LoadMaterialFromPath(MaterialPath);