How to use Instanced Materials?

The question is mainly for 4.12, but if I understand correctly this has changed over time and I’d like to also make this work with earlier versions, at least to 4.10.

I’ve Google’d far and wide and have had no definitive answer on how to do material instances in C++. So far I’ve deduced that

static ConstructorHelpers::FObjectFinder<UMaterial> MatObj(TEXT("Path To Parent Material'"));

UMaterialInstanceDynamic*  UMaterialInstanceDynamitanceDynamic::Create(MatObj.Object, this);

is supposed to be the way to go, but this causes the editor to crash - even without the class being in the level/viewport.

Do you know the trick?

If you still need it, this is I how I do it - I’m very much a UE4 beginner, so no guarantees this is optimal, but it works for me :slight_smile:

This loads the specified material (“Test_Mat”), creates a dynamic instance and sets the VectorParameter “TestColour” in it, then assigns that material to the mesh object.

// Path to material is from Content Browser, right click on material and choose "Copy Reference"
UMaterial* mat = Cast<UMaterial>(StaticLoadObject(UMaterial::StaticClass(), NULL, TEXT("Material'/Game/Test_Mat.Test_Mat'")));

if (mat != nullptr)
	UMaterialInstanceDynamic* dynamicMat = UMaterialInstanceDynamic::Create(mat, this);
	dynamicMat->SetVectorParameterValue("TestColour", FLinearColor(1,0,0));
	TestMesh->SetMaterial(0, dynamicMat);

Your version, using the ConstructorHelpers, can only be called during the C++ object’s constructor, so possibly having that marked as static is messing things up? I’m not sure, maybe someone else can comment on that.

But the one above is valid outside the constructor too (I’m calling in BeginPlay, for example).

1 Like