CreateDynamicMaterialInstance() returns nullptr

Wondering why when I use

.H
UMaterialInstanceDynamic* NewFlagMaterial;

.CPP
NewFlagMaterial = Mesh->CreateDynamicMaterialInstance(0);

NewFlagMaterial stays with a Null reference, even though I do have reference to my Mesh.

I’ve used this same setup about 3 times through my game and it works perfectly… no idea what might’ve happened.

Hello ,

Is it possible that the index that you’re supplying is invalid? From looking at the documentation for this function, it seems like that is the only time it returns a null.

Sorry for the slow response, I don’t think index is the cause of it, since I use the following :

Mesh->SetMaterial(0, xMaterial);

and it does set whatever material I put into it.

Try passing your source material along with you call, see if that helps:

void AFlag::Multicast_BlueFlagColor_Implemenation()
{
    NewFlagMaterial = Mesh->CreateDynamicMaterialInstance(0, FlagMaterials[1]);
    BlueFlagColorChange();
}

Since you’re setting the materials immediately before replacing it, this is probably a better way to go anyway.

Or maybe try:

void AFlag::Multicast_RedFlagColor_Implemenation()
{
    NewFlagMaterial = Mesh->CreateAndSetMaterialInstanceDynamicFromMaterial(0, FlagMaterials[2]);
    RedFlagColorChange();
}

Or you could try:

void AFlag::Multicast_RedFlagColor_Implemenation()
{
    NewFlagMaterial = UKismetMaterialLibrary::CreateDynamicMaterialInstance(this, FlagMaterials[2]);
    Mesh->SetMaterial(0, NewFlagMaterial);
    RedFlagColorChange();
}

Thank you for the information, I could’ve sworn I tried both of this methods out, but it appears I wasn’t placing something right. It is now returning a valid value, still not working in the Set Scalar parameter value through the timeline, but in this case it would have to be something else.

Thanks !