Download

BeginPlay is not fired for children of Component created in runtime

Hello!

Please help me register children of Component created in runtime.

I created 2 classes MyStaticMeshComponent and MyActorComponent and I’m trying to attach them to character on mouse click.
AComponentTestCharacter ∟UMyStaticMeshComponent
[INDENT=2]∟UMyActorComponent[/INDENT]

MyActorComponent::BeginPlay and TickComponent are not getting called if I construct MyStaticMeshComponent in runtime.



void AComponentTestCharacter::OnFire()
{
    MyStaticMeshComponent = NewObject<UMyStaticMeshComponent>(this);
    MyStaticMeshComponent->RegisterComponent();
    MyStaticMeshComponent->AttachToComponent(RootComponent, FAttachmentTransformRules(EAttachmentRule::KeepRelative, false));
    // ...
}

UMyStaticMeshComponent contains only 1 property and constructor.



UCLASS()
class COMPONENTTEST_API UMyStaticMeshComponent : public UStaticMeshComponent
{
    GENERATED_BODY()

public:

    UMyStaticMeshComponent();

    UPROPERTY(EditAnywhere, BlueprintReadOnly)
    UMyActorComponent* MyActorComponent;
};



UMyStaticMeshComponent::UMyStaticMeshComponent()
{
    MyActorComponent = CreateDefaultSubobject<UMyActorComponent>(TEXT("MyActorComponent"));
}


MyActorComponent just has logging added to BeginPlay.



void UMyActorComponent::BeginPlay()
{
    Super::BeginPlay();
    UE_LOG(LogTemp, Warning, TEXT("UMyActorComponent BeginPlay"));
}

Everything works perfectly fine if I create MyStaticMeshComponent in constructor of Character.



AComponentTestCharacter::AComponentTestCharacter()
{
    // ...
    MyStaticMeshComponent = CreateDefaultSubobject<UMyStaticMeshComponent>(TEXT("MyStaticMeshComponent"));
    MyStaticMeshComponent->SetupAttachment(RootComponent);
}

What am I missing here?

(I can’t initialize MyStaticMeshComponent in constructor, I have modular Pawn, I want to equip components when player picks them up).

Thank you

What fixed my problem is calling [FONT=courier new]MyActorComponent->RegisterComponent() after creating it in UMyStaticMeshComponent constructor.



UMyStaticMeshComponent::UMyStaticMeshComponent()
{
    MyActorComponent = CreateDefaultSubobject<UMyActorComponent>(TEXT("MyActorComponent"));
    MyActorComponent->RegisterComponent(); // << This helped
}


Though I still don’t understand how come it works when building UMyStaticMeshComponent in constructor with CreateDefaultSubobject and doesn’t work when building it with NewObject<UMyStaticMeshComponent>.