Static Mesh sub component doesn't move when I move my scene component

Hy,
I want to create a component “Power” with a static mesh subcomponent to visual it. This “Power” component can be attached to an actor.

Here my component Power :

#pragma once
#include "CoreMinimal.h"
#include "Components/SceneComponent.h"
#include "PowerComponent.generated.h"

UCLASS(ClassGroup = PocTest, Blueprintable, meta = (BlueprintSpawnableComponent))
class TWINSTICKSHOOTER_API UPowerComponent : public USceneComponent
{
	GENERATED_BODY()

public:	
	// Sets default values for this component's properties
	UPowerComponent();

	UPROPERTY(VisibleAnywhere)
	UStaticMeshComponent* MyStaticMesh; // <= My static mesh subcomponent 
protected:
	// Called when the game starts
	virtual void BeginPlay() override;

public:	
	// Called every frame
	virtual void TickComponent(float DeltaTime, ELevelTick TickType, FActorComponentTickFunction* ThisTickFunction) override;
	
};

Here PowerComponent.cpp :

#include "PowerComponent.h"
UPowerComponent::UPowerComponent()
{
	PrimaryComponentTick.bCanEverTick = true;

	MyStaticMesh = CreateDefaultSubobject<UStaticMeshComponent>(TEXT("SubCompStaticMesh"));
	MyStaticMesh->SetMobility(EComponentMobility::Movable);
	MyStaticMesh->SetVisibility(true, true);
	SetupAttachment(MyStaticMesh);
}

void UPowerComponent::BeginPlay()
{
	Super::BeginPlay();
}
 
void UPowerComponent::TickComponent(float DeltaTime, ELevelTick TickType, FActorComponentTickFunction* ThisTickFunction)
{
	Super::TickComponent(DeltaTime, TickType, ThisTickFunction);
}

I create an Actor with my PowerComponent and I set MyStaticMesh with a Shape_Cube to visual it.
When I move MyPowerComponent the Shape_Cube doesn’t move and it stay in the center of my actor.

I suppose the static mesh is not correctly attached to my component.
Could you help me?

I found the error :

SetupAttachment(MyStaticMesh);  

must be :

MyStaticMesh->SetupAttachment(this);

SetupAttacment take a parent as parameter not a child.
When I remove component and readd it, it’s work. The mesh is moved when I move my component.

1 Like