How to create a SphereComponent at runtime/dynamically?

It seems to me that it isn’t created. Or as it could be as you say, it potentially is created but not visible.

I didn’t try the SetHiddenInGame(false) yet, but I finally was able to have the sphere dynamically created and visible.

Here’s the updates.

// In the .h file I have this

UPROPERTY(EditAnywhere)
UStaticMesh* StaticMesh;

USphereComponent* dynamicallyCreatedSphere = nullptr;
UStaticMeshComponent* dynamicMesh = nullptr;

// In the cpp file I have this outside the constructor

void ACollidingPawnSpawnPawns::spawnPawns()
{
    if (dynamicallyCreatedSphere == nullptr) {
        //dynamicallyCreatedSphere = NewObject<USphereComponent>(USphereComponent::StaticClass()); // compiles
        dynamicallyCreatedSphere = NewObject<USphereComponent>(SphereComponent, USphereComponent::StaticClass());
        //dynamicallyCreatedSphere->SetupAttachment(SphereComponent);
        dynamicallyCreatedSphere->InitSphereRadius(30.0f);
        dynamicallyCreatedSphere->SetCollisionProfileName(TEXT("Pawn"));
        dynamicallyCreatedSphere->SetRelativeLocation(FVector(155.0f, 165.0f, 45.0f));
        dynamicallyCreatedSphere->SetVisibility(true);


        dynamicMesh = NewObject<UStaticMeshComponent>(this);
        dynamicMesh->AttachToComponent(dynamicallyCreatedSphere, FAttachmentTransformRules::KeepWorldTransform);
        dynamicMesh->RegisterComponent();
        dynamicMesh->SetStaticMesh(StaticMesh);
    }
}

Having the StaticMesh class variable declared as a UProperty allows me to select the mesh manually from UnrealEngine’s interface.

Then when I run the level that StaticMesh is used as the mesh for my class variable dynamicMesh and the dynamic component (in this case a sphere) is created and visible.

1 Like