I just want to spawn a cube...

Just setup VS studio and can now create classes but learning C++ as evidently harder than learning BPs. I’ve been searching around for a simple cube spawning example and haven’t been able to find something that’s current and works as of 4.9.

I was hoping someone here could show me how this could be done. I just want to spawn a simple cube in the level given a certain X,Y,Z coordinate.

In the header file of the class that will spawn the cube, add a property which will contain a reference to the blueprint template to instantiate.


UPROPERTY(EditAnywhere, Category = "Config")
TSubclassOf<AActor> CubeClass;

To spawn the cube you need a valid UWorld reference. The code below will work when called by an Actor derived object. Change CubeLocation to the world position where the cube should spawn.


UWorld* World = GetWorld();
if( World )
{
	const FVector CubeLocation = FVector(0, 0, 0);
	const FRotator CubeRotation = FRotator::ZeroRotator;

	AActor* CubeActor = World->SpawnActor<AActor>(
		CubeClass, CubeLocation, CubeRotation);

	if( CubeActor != nullptr )
	{
		// ...
	}
}

Hope this helps.

^ That won’t work in 4.9 because the Spawn Actor function has changed. You’ll have to give it a Transform instead of a Loc & Rot separately.

Unless I’ve got my libraries mixed up there’s still a SpawnActor override that takes location and rotation. The above compiles for me in 4.9.1 without any errors or warnings.

hey thanks a lot for this

it does compile and it runs but nothing seems to load, I tried adjusting the spawn locations by copying/pasting the coordinates from UE4 into the CubeLocation variables in Visual Studio

one thing I’m really unsure about is how can I tell if this class (default named, “MyActor”) is being called?

In the example specified, you need to create a ‘Blueprint’ version of your class, place it in the level, and also provide the Blueprint version with the object to spawn

thanks a bunch! I was finally able to pull everything together