Hi all,
I am struggling with an issue editing a parameter of a Material at runtime via C++. The premise is thus: I am implementing Chess and trying to set up an OnClick Highlight effect (using a simple Fresnel) so the player knows what piece they’ve selected. The material on the pieces looks as follows:
I modify the Tint successfully on creation of the piece in the world (I’m spawning the board and pieces programmatically), with the following code
//Initialize Piece
void APiece::InitializePiece(bool bPlayer)
{
TArray<UStaticMeshComponent*> Components;
if (bPlayer)
{
PieceColor = FLinearColor::Black;
}
else
{
PieceColor = FLinearColor::White;
}
GetComponents<UStaticMeshComponent>(Components);
//Get the Static Mesh Component
DynamicMaterial = UMaterialInstanceDynamic::Create(Components[0]->GetMaterial(0), this);
//Set the tint parameter to Black or White
DynamicMaterial->SetVectorParameterValue("Tint", PieceColor);
Components[0]->SetMaterial(0, DynamicMaterial);
bIsHighlighted = false;
}
This all works fine, it changes the base color of the pieces and sets them to white/black correctly. I have an OnClick event that calls the following function, which is where it seems to be going wrong:
void APiece::ChangeHighlight()
{
TArray<UStaticMeshComponent*> Components;
GetComponents<UStaticMeshComponent>(Components);
DynamicMaterial = UMaterialInstanceDynamic::Create(Components[0]->GetMaterial(0), this);
//If piece is not highlighted, highlight it, else remove highlight
if (!bIsHighlighted)
{
DynamicMaterial->SetScalarParameterValue("Intensity", 1.0f);
bIsHighlighted = true;
UE_LOG(LogTemp, Warning, TEXT("Setting Highlight"));
}
else
{
DynamicMaterial->SetScalarParameterValue("Intensity", 0.0f);
bIsHighlighted = false;
UE_LOG(LogTemp, Warning, TEXT("Removing Highlight"));
}
Components[0]->SetMaterial(0, DynamicMaterial);
}
When I click the actor, it turns the entire actor dark gray permanently. I’m not sure what I’m doing wrong here, but I’m pretty sure it’s in the ChangeHighlight function, as I have traced through all the other code to make sure it’s firing. Help figuring this out would be greatly appreciated!