Best practices for UMaterialInstanceDynamic?

I’m currently trying to give my mesh a material whose color can be changed programmatically. My code was working until I updated to UE 4.9, which caused the editor crashes on startup. Some of the code in my constructor:

static ConstructorHelpers::FObjectFinder<UMaterial> MaterialRef(TEXT("/Materials/M_DynamicColor.M_DynamicColor"));
UMaterialInstanceDynamic *BoxMaterial = UMaterialInstanceDynamic::Create(MaterialRef.Object, this);
BoxMesh->SetMaterial(0, BoxMaterial);

According to another AnswerHub thread, you can no longer use UMaterialInstanceDynamic::Create() in constructors. Someone suggested changing this to:

UMaterialInstanceDynamic *BoxMaterial = (UMaterialInstanceDynamic *)(MaterialRef.Object);

After this change, the editor wouldn’t crash on startup, and the material loads. However, now the editor and game crash when I try to change the material’s color property:

BoxMaterial->SetVectorParameterValue(TEXT("BaseColor"), BoxColor);

Any advice on the best way to solve this crash? Should I use UMaterialInstanceDynamic::Create(), but put it somewhere besides the constructor? Or is there a better way to create a dynamic material instance? Thanks!

I ran into something similar recently, my solution was to use the cast paradigm and put it in BeginPlay(). I can’t speak to dynamically creating and assigning a material instance in C++, as I did this in the editor, but maybe give that a try and see what happens, i.e.:

  1. Create material in editor
  2. Create material instance in editor
  3. Assign instance to mesh in editor
  4. Get object (in c++) via cast

I don’t know if that fits your needs, and I’m definitely not claiming this is the blessed way to do this, but this is what’s working for me so far, as such, I’m posting this as a comment vs an answer.

I’m actually looking to get the material to load with the object, i.e. as soon as you drop the object in the level. Thanks for the advice though!