How do you make a component with nested components?

I have some code that handles detecting something entering a USphereComponent and then attaching it to a UPhysicsConstraintComponent so I can drag it around with a player. I got it working just jamming everything into the Actor class, but I wanted to pull those components and the related code out into a self contained component of their own. Then I can slap it on future Actors that need the same functionality, and tweak the position/size of the USphereComponent and UPhysicsConstraintComponent in the editor.

Is this even possible? All my attempts have lead to something that sort of kind of looks like it might go somewhere, but end in a sea of red “Template Mismatch during attachment. Attaching instanced component to template component.” messages in the Output Console when I try to actually use the resulting component in the editor.

1 Like

This is as close as I’ve been able to get. If I try to attach the sub-components in the constructor, I get the template mismatch message. If I try to do it in BeginPlay, I get 2 errors:

LoadErrors:Error: Error /Game/MonsterHockey/Monsters/MonsterBP : Failed import for PhysicsConstraintComponent /Game/MonsterHockey/PuckHandlingComponentBP.Default__PuckHandlingComponentBP_C:PuckPhysicsConstraint
LoadErrors:Error: Error /Game/MonsterHockey/Monsters/MonsterBP : Failed import for SphereComponent /Game/MonsterHockey/PuckHandlingComponentBP.Default__PuckHandlingComponentBP_C:StickZone

and the position I set for the sub-components in the editor aren’t reflected in game.

// Sets default values for this component's properties
UPuckHandlingComponent::UPuckHandlingComponent()
{
	// Set this component to be initialized when the game starts, and to be ticked every frame.  You can turn these features
	// off to improve performance if you don't need them.
	bWantsBeginPlay = true;
	PrimaryComponentTick.bCanEverTick = true;

	// ...

	stickZone = CreateDefaultSubobject<USphereComponent>(TEXT("StickZone"));

	puckPhysicsConstraint = CreateDefaultSubobject<UPhysicsConstraintComponent>(TEXT("PuckPhysicsConstraint"));
}

// Called when the game starts
void UPuckHandlingComponent::BeginPlay()
{
	Super::BeginPlay();

	// ...
	if (stickZone != nullptr)
	{
		stickZone->AttachToComponent(this, FAttachmentTransformRules::SnapToTargetNotIncludingScale);
	}

	if (puckPhysicsConstraint != nullptr)
	{
		puckPhysicsConstraint->AttachToComponent(this, FAttachmentTransformRules::SnapToTargetNotIncludingScale);
	}
}

I’m having this error too :frowning:

ive been struggling with this on ue5.2 as well. no way to solve it yet.
other threads Unreal Engine 4.25.4 - CreateDefaultSubobject inside a child component attached to an actor loses values in blueprint editor