Can i create & attach a component inside a component ?

Oh it’s that simple ?
I always create my components in the constructor through the CreateDefaultSubobject method.
So i always thought of components as some “special” objects that should be created only in the constructor and should pre-exist in the editor.
Never thought about managing them on the fly.
This opens a lot of possibilities, i’ll definitely have to play with that !

Thanks again for another very helpful and eye opening suggestion :slight_smile:

Cedric

Take into account that NewObject works only at runtime. You will not see the components in the construction phase.

I had figured this one out.
If my understanding is correct:

  • creating in the constructor = adding to the CDO
  • creating at runtime (NewObject) = standard heap allocation

So obviously if i put all my component management at runtime, the BP will be empty in the editor.

An example I just tried and works with components

Header
UFUNCTION()
		void AddComp();

	UPROPERTY(BlueprintReadWrite, editAnywhere)
	UStaticMesh* MeshTest;


CPP

// added input bind in cpp in SetupPlayerInputComponent
PlayerInputComponent->BindAction("AddComp", IE_Pressed, this, &AmcCharacter::AddComp);


void AmcCharacter::AddComp() {
	if (MeshTest != nullptr) {
		UStaticMeshComponent* comp = NewObject<UStaticMeshComponent>(this, UStaticMeshComponent::StaticClass(), TEXT("MyComp"));
		comp->RegisterComponent();
		comp->SetStaticMesh(MeshTest);
		comp->AttachToComponent(GetRootComponent(), FAttachmentTransformRules::SnapToTargetNotIncludingScale);
	}
}

Yes all NewObjects need to be managed more tightly so you need to destroy them if not needed.
Maybe you need to pass them to a TArray that is a uproperty if they are garbage collected. (I’ve only used NewObject for actors so not sure of their lifecycle)

Cool example, and that’s great news, this will definitely change the way i think about components.
I’ll make some tests on my side and will reorganize my code accordingly.

The life cycle in my case shouldn’t be too hard to handle: create everything at possession, and destroy everything at unpossession.

Again, thanks a ton for your time and help, very appreciated !