Hi,
I have also tried creating an UMaterialInstanceDynamic in the Constructor in C++. I had issues by using UMaterialInstanceDynamic::Create in the constructor and the solution of RuneBerg posted on May 20 '18 helped me.
But then I had troubles when I was realoading my world (When I quit Unreal studio and relaunched later my project). The MaterialInstanceDynamics were no longer there.
So, if anyone have the same issue, here is the solution that I found.
Don’t create the the material instance dynamic in the constructor at all. Put your code inside PostActorCreated(). That way, it’s like the MID is created outside the constructor and… well I don’t know why but that don’t create the same issues that it does in the constructor.
/// Header file
/**
* Called after the constructor.
* Used to create the material instance dynamic of the cables.
* Can't be create directly in the contructor because it will not be created again on the reload of the world.
*/
virtual void PostActorCreated() override;
/// Cpp file
void AITPowerSupplySystem::PostActorCreated()
{
UE_LOG(LogTemp, Warning, TEXT("[%s] PostActorCreated"), *this->GetName());
Super::PostActorCreated();
for (uint8 i = 0; i < this->NumberCables; i++)
{
if (this->PowerSupplySystemCables.IsValidIndex(i))
{
UCableComponent* Cable = this->PowerSupplySystemCables[i].Components.Cable;
const FString CableMaterialRef = TEXT("Material'/Game/Materials/M_Cable.M_Cable'");
UMaterialInterface* const CableMaterialFinder = LoadObject<UMaterialInterface>(Cable, *CableMaterialRef);
if (CableMaterialFinder)
{
Cable->SetMaterial(0, UMaterialInstanceDynamic::Create(CableMaterialFinder, Cable));
UE_LOG(LogTemp, Warning, TEXT("[%s] create Material name : %s"), *this->GetName(), *Cable->GetMaterial(0)->GetName());
}
else
{
UE_LOG(LogTemp, Error, TEXT("[%s] Impossible to find UMaterial : %s"), *this->GetName(), *CableMaterialRef);
}
}
}
}