6. Creating and editing the dynamic material

Before we can create our dynamic material, we need to find our static mesh component that contains our material.

Img 23, Code of finding our static mesh component and creating and setting our dynamic mesh


With the “GetComponentByClass()” function we are asking UE4 to return to us the first component object defined within the round brackets. We want to receive our static mesh component, so we use “UStaticMeshComponent::StaticClass()”. The function returns a “UComponent*”. With the “Cast<T>()” function we can convert the returned object between the round brackets to our class defined in position of “T”. 


We use the “IsValid()” function as a security to make sure that the cast has been executed successfully. If the cast has failed and we were to try to access an empty pointer, our game would instantly crash. Within the if-statement we put the rest of our code.


Line 25 on image 23 creates a dynamic material and assigns it to our pointer. Within the function we use “SMC->GetMaterial(0)” to access our material in the static mesh component.


Then we use “SMC->SetMaterial()” to replace our material in the static mesh component with our dynamic material.


Now our dynamic material has been set up, we can start adding effects to our dynamic material. Let’s give our dynamic material a random color and random emission intensity.

Img 24, Setting a random emission color and emission strength


On lines 28 to 31 you can see an example of how to create a random color. On line 32, we are going to adjust a vector parameter in our dynamic material. My parameter name for our vector parameter was “EmissionColor”, which is the first parameter slot of the function. In the second parameter slot of the function we tell what color to set, we use our random color “RandomColor”.


Editing a scalar parameter is similar, but we use the function “SetScalarParameterValue()” instead. My scalar parameter name was “EmissionStrength”.


Your total code should look like this:

Img 25, Total code of the dynamic material with effect


Popular posts from this blog

5. Constructing a blueprint

8. Reading parameters of the dynamic material