SetVectorParameterValue working only for the 1rst time?

Hey guys, I’ve been struggling with this for the past 2 days and havent been able to figure this out, im pretty sure is something really simple that I’m missing, so maybe anyone can help me :slight_smile:

What im trying to do: Change a color through a function

CitySegment.h

UPROPERTY(Category = Meshes, VisibleAnywhere)
UStaticMeshComponent *segmentMesh;

UPROPERTY(Category = Materials, EditAnywhere)
UMaterialInterface *originalMaterial;//initialized in the details menu in the UE Editor

UMaterialInstanceDynamic *segmentMaterialInstance;

CitySegment.cpp


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

    segmentMaterialInstance = UMaterialInstanceDynamic::Create(originalMaterial,this);
    if(segmentMaterialInstance->IsValidLowLevel()) {
        segmentMesh->SetMaterial(0, segmentMaterialInstance);
        segmentMaterialInstance->SetVectorParameterValue(FName(TEXT("SegmentColor")),FLinearColor(1,1,0, 1.0)); //<-- change the color to yellow
    } else {
        UE_LOG(LogTemp, Error, TEXT("Not valid material low level!"));
    }
}

In theory after calling “BeginPlay” the color of the is yellow.

Later in the code I call this function:

void ACitySegment::SetSegmentColor(const float &r, const float &g, const float &b) {
    segmentMaterialInstance = UMaterialInstanceDynamic::Create(originalMaterial,this);
    if(segmentMaterialInstance) {
        segmentMesh->SetMaterial(0, segmentMaterialInstance);
        segmentMaterialInstance->SetVectorParameterValue(FName(TEXT("SegmentColor")),FLinearColor(r, g, b, 1.0));
    } else {
        UE_LOG(LogTemp, Error, TEXT("Material instance not found!"));
    }
}

With this value: SetSegmentColor(1,0,0); //<-- change the color to red

But the color stays Yellow! :S. Any idea what’s happening here?

One more thing; I noticed that if I dont put any code in BeginPlay (regarding changing color) and then call the function SetSegmentColor() it changes its color how it should… :confused:
Thanks a bunch!

When your BeginPlay function is called, you create a new DynamicMaterial having the originalMaterial as a parent. When SetSegmentColor is called you create a new DynamicMaterial having the new DynamicMaterial from BeginPlay as a parent. A DynamicMaterial can’t be a parent for another DynamicMaterial.

Try getting rid of the creation of the DynamicMaterial in your SetSegmentColor function and keep the rest and that should fix your issue.

Let me know if that works.

Thanks for the reply!, I tried that out, if I remove the

segmentMaterialInstance = UMaterialInstanceDynamic::Create(originalMaterial,this);

inside SetSegment() I always get the error “Material instance not found!” from the UE_LOG :-/. Somehow the segmentMAterialInstance pointer ref is lost; could it be that is somehow garbage collected by the engine?.