attach and change material base color with c++

Hi all,

Is this possible attach dynamically (with c++) a material to an actor static mesh, and to dynamically (still with c++) change the base color of this material ?

Hi!

Yep, it is possible. For example in AYourActor::BeginPlay you can do something like this:



if (materialBase)
  dynamicMaterial = UMaterialInstanceDynamic::Create(materialBase, this);
mesh->SetMaterial(0, dynamicMaterial);


where

materialBase - basic material for dynamic instanced material
dynamicMaterial - dynamic instanced material that you can modify
mesh - your static mesh

You can change color via material parameters. Using methods: SetScalarParameterValue, SetVectorParameterValue. For example:



dynamicMaterial->SetVectorParameterValue(TEXT("Color"), FLinearColor::Red);


Thanks a lot

Hi, Thanks for this but I am still having a problem. I did EXACTLY what you posted and it doesn’t work:

Code: [TABLE=“border: 1, cellpadding: 1, width: 500”]

void AFloatingActor::BeginPlay()
{
Super::BeginPlay();

		auto Cube = FindComponentByClass<UStaticMeshComponent>();
		auto Material = Cube->GetMaterial(0);

		DynamicMatierial = UMaterialInstanceDynamic::Create(Material, this);
		Cube->SetMaterial(0, DynamicMatierial);

		qColor.A = 0.0;
		qColor.R = 120.0;
		qColor.G = 200.0;
		qColor.B = 36.0;
		FLinearColor fColor(100.0, 23.0, 233.0);
		FVector vColor(100.0, 23.0, 233.0);

		DynamicMatierial->SetVectorParameterValue(FName(TEXT("QbColor")), FLinearColor::Red);
		}

Thanks for any help!

Make sure that:

  1. the shape has the material applied;
  2. the material has a “QbColor” vector parameter connected to the “Base Color” pin.

What does “doesn’t work” mean?
If you step through it in the debugger, what does it do?
Is any variable NULL?
Can you step into SetVectorParameterValue() and see what it does?

Thanks for the quick responses. I noticed the error a little while ago and fixed it - newb here.

Cheers!