Setting dynamic material instance color C++

Hello, I am trying to change material color of standard UE4 Mannequin skeletal mesh but there is nothing hapenning both in viewport and in game.

   AEnemyBase::AEnemyBase()
    {
    	mesh_ = GetMesh();
    	mesh_->SetupAttachment(GetCapsuleComponent());	
    
    	TArray<class UMaterialInterface*> materials = GetMesh()->GetMaterials();
    	for (int i = 0; i < materials.Num(); i++)
    	{
    		UMaterialInstanceDynamic* matInstance_ = UMaterialInstanceDynamic::Create(materials[i], this);
    
    		matInstance_->SetVectorParameterValue(FName(TEXT("_BodyColor")), characterColor);
    		GetMesh()->SetMaterial(i, matInstance_);
    	}
    }

Hey there, first of all you dont need the FName(TEXT, just do “_BodyColor”, what you are doing there is kind of the same as doing 3 + 1 - 1, instead of using just 3. Second, i would create the dynamic material in the begin play and using this command:

UMaterialInterface * Material = GetMesh()->GetMaterial(i);
UMaterialInstanceDynamic* matInstance = GetMesh()->CreateDynamicMaterialInstance(i, Material);

if(matInstance != nullptr)
     matInstance->SetVectorParameterValue("_BodyColor", characterColor);

See if that works.

Hey, thanks for your answer, it works perfectly as it should.

But do you have any idea why code that you’ve sent works in BeginPlay but doesn’t work in class contructor?

Hey good to know, the inner code of unreal probably has some verification that prevents it from running on the contructor.