Change character's material at runtime using c++

Found the issue

I found the issue last week and I thought I would let you guys know in case someone have a similar issue. On every frame I was creating a new dynamic material instance and setting it as the new material for that mesh. That worked for the first frame, but on the second frame it was complaining because the parent material (which is now a dynamic material) is not a valid parent for a dynamic material. The solution was to put the code to create the material in BeginPlay and then set the material each frame, so now the dynamic material is only created once, but change each frame.

Here is the BeginPlay function:



void ABatteryCollectorCharacter::BeginPlay()
{
	Super::BeginPlay();
	DynamicMaterial = UMaterialInstanceDynamic::Create(GetMesh()->GetMaterial(0), this);
}


And here is my function that is called every frame:



void ABatteryCollectorCharacter::PowerChangeEffect()
{
	float PowerRatio = FMath::Clamp((CharacterPower / InitialPower), 0.0f, 1.0f);
	FLinearColor PowerRatioColor = FMath::Lerp(Teal, Orange, PowerRatio);
	DynamicMaterial->SetVectorParameterValue("BodyColor", PowerRatioColor);
	GetMesh()->SetMaterial(0, DynamicMaterial);
}