I need to create Static Mesh subcomponents in hierarchy inside the BeginPlay() function of an actor.
I have no problems creating a hierarchy of components inside the constructor. This is how I do it there and there’s no problem with this part:
MyActor.h:
...
UPROPERTY(VisibleAnywhere, BlueprintReadOnly)
UStaticMeshComponent* Father;
UStaticMeshComponent* Son;
...
MyActor.cpp:
...
AMyActor::AMyActor {
Father = CreateDefaultSubobject<UStaticMeshComponent>("Father");
Son = CreateDefaultSubobject<UStaticMeshComponent*>("Son");
RootComponent = Father;
Son->SetupAttachment(Father);
}
Now I need to attach a new child component to “Son” inside the BeginPlay() function. That’s where the problem starts. This is how I do it:
UStaticMeshComponent* GrandSon = NewObject<UStaticMeshComponent>(Son, UStaticMeshComponent::StaticClass());
GrandSon->RegisterComponent();
With this approach, the new component “GrandSon” is spawned, but not as a child of “Son”. It is spawned as a child of “Father”. It is never attached to “Son”.
I tried using the method USceneComponent::AttachToComponent() but nothing changes. GrandSon is still spawned as a brother to Son insted of a subcomponent.