How to spawn a simple cube in C++?

I know there’s 1 or 2 questions out there like this, but I need a definitive and concise answer.

All I need to be able to do is spawn a cube at a position that I define and spawn it when I tell it to be spawned. That’s it, very simple however I can’t seem to get it to work at all. I’ve tried several different options but with no luck.

Any help would be greatly appreciated.

Beginner here, but ill give it a go:

Create a new project, then extract the static mesh from the box brush as detailed here.

Save it somewhere

Go File->AddCodeToProject
Add a new actor, call it ‘CubeActor’

Exit from the unreal editor

change CubeActor.h to the following:

UCLASS()
class SOMEPROJECT_API ACubeActor : public AActor
{
	GENERATED_UCLASS_BODY()

	UPROPERTY(Category = Meshes, VisibleAnywhere)
	TSubobjectPtr<UStaticMeshComponent> CubeMesh;
    	
    };

Change CubeActor.cpp to the following:

ACubeActor::ACubeActor(const class FPostConstructInitializeProperties& PCIP)
	: Super(PCIP)
{
	CubeMesh = PCIP.CreateDefaultSubobject<UStaticMeshComponent>(this, TEXT("CubeMesh"));
}

Recompile your project, should build fine.

Back in the editor , select new from the content browser in the bottom left, select blueprint - select your newly created CubeActor:

22966-parentclass.png

save your blueprint as ‘BP_Cube’

Open up your new blueprint.
Under ‘Defaults’, choose the static mesh you saved eariler:

Compile and save your blueprint.

Close the editor

Now thats done, you’ll want to change your ACubeActor to the following:

UCLASS()
class SOMEPROJECT_API ACubeActor : public AActor
{
	GENERATED_UCLASS_BODY()

	UPROPERTY(Category = Meshes, VisibleAnywhere)
	TSubobjectPtr<UStaticMeshComponent> CubeMesh;

public:
	TSubclassOf<class ACubeActor> CubeBlueprint;
};

ACubeActor.cpp:

ACubeActor::ACubeActor(const class FPostConstructInitializeProperties& PCIP)
	: Super(PCIP)
{
	CubeMesh = PCIP.CreateDefaultSubobject<UStaticMeshComponent>(this, TEXT("CubeMesh"));

	static ConstructorHelpers::FObjectFinder<UBlueprint> CubeBP(TEXT("Blueprint'/Game/BP_Cube.BP_Cube'"));
	if (CubeBP.Object){
		CubeBlueprint = (UClass*)CubeBP.Object->GeneratedClass;
	}
}

Now, you’ll want to add a new header library (this is so we can have a reference to cube blueprint anywhere)

Create ‘BP_Libs.h’ (if you build it straight in VS, it’ll put it by default in intermediate/projectfiles/, you’ll need to move this to source/someproject/ to be able to reference it)

then add the following:

#include "SomeProject.h"

static TSubclassOf<class ACubeActor> GetCubeBP()
{
	static ConstructorHelpers::FObjectFinder<UBlueprint> CubeBP(TEXT("Blueprint'/Game/BP_Cube.BP_Cube'"));
	if (CubeBP.Object){
		return (UClass*)CubeBP.Object->GeneratedClass;
	}
}

template <typename ObjectType>
static FORCEINLINE ObjectType* SpawnBP(
	UWorld* TheWorld,
	UClass* TheBP,
	const FVector& Loc,
	const FRotator& Rot,
	const bool bNoCollisionFail = true,
	AActor* Owner = NULL,
	APawn* Instigator = NULL
	){
	if (!TheWorld) return NULL;
	if (!TheBP) return NULL;
	//~~

	FActorSpawnParameters SpawnInfo;
	SpawnInfo.bNoCollisionFail = bNoCollisionFail;
	SpawnInfo.Owner = Owner;
	SpawnInfo.Instigator = Instigator;
	SpawnInfo.bDeferConstruction = false;

	return TheWorld->SpawnActor<ObjectType>(TheBP, Loc, Rot, SpawnInfo);
}

Credits to rama: A new, community-hosted Unreal Engine Wiki - Announcements - Epic Developer Community Forums
and the guys over here: Spawn Blueprint from C++ - Editor Scripting - Epic Developer Community Forums

Then you can create the cube like this:
(I just used my gamemode constructor)

#include "BP_Libs.h"

ASomeProjectGameMode::ASomeProjectGameMode(const class FPostConstructInitializeProperties& PCIP)
	: Super(PCIP)
{
	FVector Position = FVector(0, 0, 0);
	FRotator Rotation = FRotator(0);
	SpawnBP<ACubeActor>(GetWorld(), GetCubeBP(), Position, Rotation);
}

I also added the full source here, if you want to pick through it:

Thank you for such a concise response it has really helped. Although now I’m having the problem that I am unable to spawn anything because GetWorld() comes up with the error: 'a nonstatic member reference must be relative to a specific object. I’m pretty sure it’s because this is being used in a static function. Is there any way around this?

Hey, your right - i didnt actually compile this before posting. Ive corrected my answer to a working solution (with help of google) and ive actually tested it this time!

Funny thing about this is that even if you change the position of the FVector the starting position does not change. It continues to spawn in the same place. The only thing that does change is the number inside of the transform panel of the editor.

This is still an incredibly useful answer. +1

hey, found the answer. It seems like it’s necessary to move the mesh, not the actor.

for my code I already overrode BeginPlay() in CubeActor.h

	UPROPERTY(Category = Meshes, VisibleAnywhere)
			UStaticMeshComponent *CubeMesh;
public:	

	// Called when the game starts or when spawned
	virtual void BeginPlay() override;

MycubeActor.cpp

   // Called when the game starts or when spawned
    void AViewCubeActor::BeginPlay()
    {
    	Super::BeginPlay();
    	//SetActorLocation(FVector(0.f, 0.f, 300.0f));
    	CubeMesh->SetMobility(EComponentMobility::Movable);
    	FTransform relTrans = CubeMesh->GetRelativeTransform();
    	FVector loc = CubeMesh->GetComponentLocation();
    	FVector position = FVector(loc.X, loc.Y, loc.Z + 300.0f);
    	relTrans.SetLocation(FVector(position));
    	CubeMesh->SetRelativeTransform(relTrans);
    }

What I just did isn’t a good way to do it. Just set CubeActor’s RootComponent to CubeMesh in its constructor. That way everything stays together instead of having to update both the mesh and the actor separately.

Woo.

This tutorial is now deprecated (>4.8) so it throws thousands of errors, so disregard it until updated.

Can someone please show me a 5-10 step tutorial on how to spawn actor in C++ or a ten minute video?

Are you kidding me?
All this actions i must make to spawn simple cube?

I’m don’t have an experience in Unreal Engine and i think it will not be.

This is very old code, and has been deprecated since v4.8.
To spawn a cube (v4.11):

UCLASS()
class ABox : public AActor {
    GENERATED_BODY()
public:
    ABox(const FObjectInitializer& ObjectInitializer) {
        auto box = ObjectInitializer.CreateDefaultSubobject<UBoxComponent>(this, FName("My Box"));
        box->bHiddenInGame = false;
        box->Mobility = EComponentMobility::Movable;
        RootComponent = box;
    }
}

…and then:

auto loc = GetActorLocation();
loc.Z += 300.0f;
GetWorld()->SpawnActor<ABox>(loc, GetActorRotation());

I wrote this, but i didn’t see anything on scene. May be cube was invisible?

In order to use this tutorial for Unreal Engine 4.12,
CubeActor.h:

UCLASS()
 class SOMEPROJECT_API ACubeActor : public AActor
 {
     GENERATED_BODY()
 
     UPROPERTY(Category = Meshes, VisibleAnywhere)
     UStaticMeshComponent* CubeMesh;
 
 public:
     TSubclassOf<class ACubeActor> CubeBlueprint;
     ACubeActor(const FObjectInitializer& ObjectInitializer);

 };

And, CubeActor.cpp:

ACubeActor::ACubeActor(const FObjectInitializer& ObjectInitializer) : Super(ObjectInitializer)
 {
     CubeMesh = ObjectInitializer.CreateDefaultSubobject<UStaticMeshComponent>(this, TEXT("CubeMesh"));
 
     static ConstructorHelpers::FObjectFinder<UBlueprint> CubeBP(TEXT("Blueprint'/Game/BP_Cube.BP_Cube'"));
     if (CubeBP.Object){
         CubeBlueprint = (UClass*)CubeBP.Object->GeneratedClass;
     }
 }

I just did the thing you want.

In constructor:

	static ConstructorHelpers::FObjectFinder<UStaticMesh> pCube(TEXT("StaticMesh'/Game/Geometry/Meshes/1M_Cube.1M_Cube'"));
	pCubeMesh = pCube.Object;

In BeginPlay:

	AStaticMeshActor* NewBlock = GetWorld()->SpawnActor<AStaticMeshActor>(FVector(300,-200,0), FRotator(0, 0, 0));
	NewBlock->SetActorScale3D(FVector(1, 1, 0.1f));
	NewBlock->SetMobility(EComponentMobility::Movable);
	TArray<UStaticMeshComponent*> Comps;
	NewBlock->GetComponents(Comps);
	if (Comps.Num() > 0)
	{
		UStaticMeshComponent* FoundComp = Comps[0];
		FoundComp->SetStaticMesh(pCubeMesh);
	}