I created a Blueprint from a C++ class. In that Blueprint, I added a static mesh component (a plane). This plane uses a simple material, only a color.
I want to be able to change the color of this plane, progressively in the C++ class.
I investigated two strategies: Creating 2 materials and switching from one to the other, or creating a material with 2 colors, and using a lerp function. The second strategy seems more accessible, but I still need help on that.
So here is how I set up the material: 2 colors, 1 lerp function to blend the colors, and a scalar parameter that I called “Blend” to input the proportion of each color in the blend.
In my C++ class I can access to the material with this code:
auto Plane = FindComponentByClass<UStaticMeshComponent>();
auto material = Plane->GetMaterial(0);
Then, what I would like to do in the C++ class is something like
SetScalarParameterValue(TEXT("Blend"), value);
But there is no such function… There is only a
GetScalarParameterValue()
.
Any idea how I could modify the scalar parameter from the C++ class?
I would also be interested in another way to change the color from the C++ class if there is better strategy.
Thanks!
##EDIT: SOLUTION
Following Roel advices, I created a MaterialInstanceDynamic, and called SetScalarParameterValue()
on this MaterialInstanceDynamic.
In the .f file I added:
UMaterialInstanceDynamic* DynamicMaterial;
In the .cc file I added:
void AMyPlane::BeginPlay()
{
Super::BeginPlay();
auto Plane = FindComponentByClass<UStaticMeshComponent>();
auto material = Plane->GetMaterial(0);
DynamicMaterial = UMaterialInstanceDynamic::Create(material, NULL);
Plane->SetMaterial(0, DynamicMaterial);
}
void AMyPlanel::Tick(float DeltaTime)
{
Super::Tick(DeltaTime);
// Testing the color switch at runtime
float blend = 0.5f + FMath::Cos(GetWorld()->TimeSeconds)/2;
DynamicMaterial->SetScalarParameterValue(TEXT("Blend"), blend);
}
###Result