I need to Spawn a component and attach it to another when i press a action mapping (C).
Every time i try this method SpawnChildren the UE4 breaks.
Here the .h (simplified)
UCLASS()
class HOWTO_COMPONENTS_API ACollidingPawn : public APawn
{
GENERATED_BODY()
private:
UPROPERTY()
UStaticMeshComponent* OrbitSphereVisual;
UFUNCTION()
void SpawnChildren();
UPROPERTY()
float SpawnTime;
};
The .cpp (simplified)
ACollidingPawn::ACollidingPawn()
{
PrimaryActorTick.bCanEverTick = true;
USphereComponent* SphereComponent = CreateDefaultSubobject<USphereComponent>(TEXT("RootComponent"));
RootComponent = SphereComponent;
SphereComponent->InitSphereRadius(40.0f);
SphereComponent->SetCollisionProfileName(TEXT("Pawn"));
UStaticMeshComponent* SphereVisual = CreateDefaultSubobject<UStaticMeshComponent>(TEXT("VisualRepresentation"));
SphereVisual->SetupAttachment(RootComponent);
static ConstructorHelpers::FObjectFinder<UStaticMesh> SphereVisualAsset(TEXT("/Game/StarterContent/Shapes/Shape_Sphere.Shape_Sphere"));
if (SphereVisualAsset.Succeeded())
{
SphereVisual->SetStaticMesh(SphereVisualAsset.Object);
SphereVisual->SetRelativeLocation(FVector(0.0f, 0.0f, -40.0f));
SphereVisual->SetRelativeScale3D(FVector(0.8f));
}
OrbitSphereVisual = CreateDefaultSubobject<UStaticMeshComponent>(TEXT("OrbitSphereVisual"));
OrbitSphereVisual->SetupAttachment(SphereComponent);
static ConstructorHelpers::FObjectFinder<UStaticMesh> OrbitSphereVisualAsset(TEXT("/Game/StarterContent/Shapes/Shape_Sphere.Shape_Sphere"));
if (OrbitSphereVisualAsset.Succeeded())
{
OrbitSphereVisual->SetStaticMesh(OrbitSphereVisualAsset.Object);
OrbitSphereVisual->SetRelativeLocation(FVector(0.0f, 100.0f, 0.0f));
OrbitSphereVisual->SetRelativeScale3D(FVector(0.2f));
}
}
// Called when the game starts or when spawned
void ACollidingPawn::BeginPlay()
{
Super::BeginPlay();
}
// Called to bind functionality to input
void ACollidingPawn::SetupPlayerInputComponent(UInputComponent* PlayerInputComponent)
{
Super::SetupPlayerInputComponent(PlayerInputComponent);
PlayerInputComponent->BindAction("Spawn", IE_Pressed, this, &ACollidingPawn::SpawnChildren);
}
void ACollidingPawn::SpawnChildren()
{
UStaticMeshComponent* newMesh = NewObject<UStaticMeshComponent>(this->GetOwner());
newMesh->SetupAttachment(OrbitSphereVisual);
static ConstructorHelpers::FObjectFinder<UStaticMesh> newMeshAsset(TEXT("/Game/StarterContent/Shapes/Shape_Sphere.Shape_Sphere"));
if (newMeshAsset.Succeeded())
{
newMesh->SetStaticMesh(newMeshAsset.Object);
newMesh->SetRelativeLocation(FVector(0.0f, 50.0f, 0.0f));
}
}