I have a base CPP class that attempts to dynamically set material instances in OnConstruction:
void ACPP_MyActorBase::OnConstruction(const FTransform& Transform)
{
// Setup Dynamic Material Instances
for (UActorComponent *Component : GetComponentsByClass(UMeshComponent::StaticClass())) {
UMeshComponent* MeshComponent = Cast<UMeshComponent>(Component);
UMaterialInterface *Material = MeshComponent->GetMaterial(0);
UMaterialInstanceDynamic *DynamicMaterialInstance = MeshComponent->CreateDynamicMaterialInstance(0, Material);
DynamicMaterials.Add(DynamicMaterialInstance);
)));
}
}
I’ve been scratching my head as to why this array is empty when trying to access in my subclass’s blueprint. I ended up putting a getter to access the function that looks like this:
TArray<UMaterialInstanceDynamic*> ACPP_MyActorBase::GetDynamicMaterials()
{
return DynamicMaterials;
}
I added some logging and stripped my code to the bare minimum, even trying to do this with a simple TArray of integers. It turns out the problem is fairly simple: the call to GetDynamicMaterials is happening before the parent OnConstruction call. Here’s the construction script of my blueprint which is a subclass of ACPP_MyActorBase:
I’m really baffled. I thought perhaps there was a race condition with threads, but when I pop open the debugger in visual studio, both OnConstruction and GetDynamicMaterials appear to be running in the same main thread with the same thread ID.
Why is this happening? How can I make sure the constructor has fully executed before I do other things to the object?