Object in the world loses dynamic instanced material when C++ is compiled

I’m having a weird problem when assigning dynamic instances of a material to a component in the C++ constructor of an actor.

Basically I’ve got this actor, made up of 3 static mesh components:

The code to create it and to assign it the material looks like this:



ARotationWidget::ARotationWidget()
{
    PrimaryActorTick.bCanEverTick = false;

    // Creating the mesh
    FName meshName = TEXT("/Engine/VREditor/TransformGizmo/RotationHandleFull");
    UStaticMesh *rotationHandleMesh = Cast<UStaticMesh>(StaticLoadObject(UStaticMesh::StaticClass(), NULL, *meshName.ToString()));

    // Loading the material
    FName matName = TEXT("Material'/Game/BaseMaterial.BaseMaterial'");
    UMaterial* mat = Cast<UMaterial>(StaticLoadObject(UMaterial::StaticClass(), NULL, *matName.ToString()));

    // Creating a dynamic instance of the material
    UMaterialInstanceDynamic *XdynamicMaterial = UMaterialInstanceDynamic::Create(mat, GetTransientPackage());
    XdynamicMaterial->SetVectorParameterValue("Color", FVector(1, 0, 0));

    // Creating the component
    XaxisCircle = CreateDefaultSubobject<UStaticMeshComponent>(TEXT("XaxisCircle"));
    XaxisCircle->SetStaticMesh(rotationHandleMesh);
    XaxisCircle->SetMaterial(0, XdynamicMaterial);

    // The rest of the code looks pretty much the same; it creates the other 2 components

}



When I compile the C++ classes, the components’ dynamic materials vanish leaving their default material, like this:

What am I doing wrong here?

As far as I know, you shouldn’t do that in the constructor. Try getting/setting your MID in BeginPlay().

That’s what I ended up doing for the moment. But I don’t understand why it works that way if done in the constructor…