How to spawn the basic cube through C++

Well key is to learn how to add components to C++ actor in .h you you decler component:

UPROPERTY()
TSubobjectPtr<UBoxComponent> Box;

and in class constructor you add:

Box = PCIP.CreateDefaultSubobject<USkeletalMeshComponent>(this, TEXT("Box")); //init
//set varables, in our case we making box visible in game
Box->bHiddenInGame = false;
//set component as root
RootComponent = Box;

or if you already have Root component set

AddComponent(FName("Box"), false, FTransform(), NULL);

with FName you use in component initiation. Now you can spawn box with this function:

()->SpawnActor(ABox::StaticClass());

Just replace ABox with class name of your box. SpawnActor also accepts more aguments lik positioning and rotation of spawned object. You can do this with any component (for static mesh you would use UStatiicMeshComponent for example), here you got full list of them:

1 Like