How can I spawn a sphere in C++?

Hey guys, I have been trying for a while now and I cannot seem to get this.
It continuasly crashes with : CreateDefultSubobject can only be used inside of UObject constructors. UObject constructing subobjects ca

.CPP:
void AGameManager::SphereFactory()
{   
	SphereComponent = CreateDefaultSubobject<USphereComponent>(TEXT("RootComponent"));
}
.h:
	USphereComponent* SphereComponent;

What and why is not letting me create this?

This is a known limitation, and the error message is correctly pointing it out. I’m not sure why “CreateDefaultSubobject” is not allowed outside of the constructor.

I think you can use ContstructObject instead, e.g.

  //Create Component
  SphereComponent = ConstructObject<USphereComponent>(USphereComponent::StaticClass, this, TEXT("MySphereComponent"));
  if(SphereComponent) 
 {    
		// Register the component
		SphereComponent->RegisterComponent();
		
		// Attach to root component
		SphereComponent->AttachTo(GetRootComponent()); 
		  
		// or make it the rootcomponent - haven't tested this
		RootComponent = SphereComponent;
}

Two years, working on it every single day, TWO LONG YEARS FINALLY!

ACell::ACell(const FObjectInitializer& ObjectInitializer) : Super(ObjectInitializer)
{
 	// Set this actor to call Tick() every frame.  You can turn this off to improve performance if you don't need it.
	PrimaryActorTick.bCanEverTick = false;

	USphereComponent* box = ObjectInitializer.CreateDefaultSubobject<USphereComponent>(this, FName("My Box"));
	box->bHiddenInGame = false;
	box->Mobility = EComponentMobility::Movable;
	RootComponent = box;

	UStaticMeshComponent* SphereMesh = CreateDefaultSubobject<UStaticMeshComponent>(TEXT("VisualRepresentation"));
	SphereMesh->AttachTo(RootComponent);
	static ConstructorHelpers::FObjectFinder<UStaticMesh> SphereMeshAsset(TEXT("/Game/StarterContent/Shapes/Shape_Sphere.Shape_Sphere"));
	if (SphereMeshAsset.Succeeded()) {
		SphereMesh->SetStaticMesh(SphereMeshAsset.Object);
		SphereMesh->SetRelativeLocation(FVector(0.0f, 0.0f, 0.0f));
		SphereMesh->SetWorldScale3D(FVector(0.8f));
	}
}

Nah just kidding, took me an hour once I learned c++.

sorry, but the effort to spawn a simple sphere in unreal from code is just ridicoulous …

BTW, you did not spawned sphere but created actor with sphere component and mesh component

FYI, you can reference the engine sphere at StaticMesh’/Engine/BasicShapes/Sphere.Sphere’

If I put the above code in a loop with >2 iterations, it crashes the editor…

watch this. How To Do Line Tracing Using C++ In Unreal Engine - YouTube