Can't set scalar parameter at runtime.

The class extends a character.

(obiously this doesn’t show the entire files)

.h file:
// Matieral for dynamic glow.
UPROPERTY(VisibleDefaultsOnly, BlueprintReadOnly, Category = “Power”)
class UMaterialInstanceDynamic* DynamicMaterial;

In Constructor:
DynamicMaterial = Mesh->CreateAndSetMaterialInstanceDynamic(0);

In Tick():
DynamicMaterial->SetScalarParameterValue(FName(TEXT(“PowerMultiplier”)), 1.0f);

When I compile then play the game the editor crashes even though I am 100% sure the parameter name is typed in correctly in the meterial editor and code.

What did I do wrong?


I figured it out. The mesh wasn’t defined in the constructor so the dynamic material had to be set later. I removed the line in the constructor and put this in the Tick() event:

if (!DynamicMaterial)
DynamicMaterial = GetMesh()->CreateAndSetMaterialInstanceDynamic(0);
DynamicMaterial->SetScalarParameterValue(FName(TEXT(“PowerMultiplier”), 1.0f);

Also, you can’t create MIDs in UObject constructors. All of the existing methods for constructing MIDs are meant for runtime creation and do not set the required flags for proper handling of subobjects. That could probably be worked around by adding a new creation function for it, but yeah.

If you want, you can also initialize the MID in PostInitializeComponents() instead of a lazy init in Tick(). That’s what I usually do.


I am new so I didn’t know about the PostInitializeComponents()
I will use that.