How To Spawn Actor From Blueprint in C++

I’ve tried following several guides however I can not get it to work at all.

In my Helicopter3DGameMode.h I have:

UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = Classes)
TSubclassOf<class ABasicTile> BasicTileBPClass;

I then have a blueprint child game mode, Helicopter3DGameMode_BP.h where I have set the BasicTileBPClass to be BasicTile_BP which is a blueprint child of ABasicTile.

In Helicopter3DGameMode.cpp I have:

AHelicopter3DGameMode::AHelicopter3DGameMode()
{
	Tiles = TArray<ABasicTile*>();

	if (BasicTileBPClass != nullptr)
	{
		FActorSpawnParameters SpawnParams;
		SpawnParams.bNoCollisionFail = true;
		auto NewTile = GetWorld()->SpawnActor<ABasicTile>(BasicTileBPClass, SpawnParams);

	}
	else
	{
		GEngine->AddOnScreenDebugMessage(-1, 5.f, FColor::, TEXT("BasicTileBPClass is null"));
	}
}

I made sure to set the default game mode to my Helicopter3DGame_BP in the maps and modes settings however every time I run the game BasicTileBPClass is null despite being set in the blueprint editor. What am I doing wrong?

Hello tohei,

You’ll need to move your spawning logic to another function that is run at runtime. There are two problems with having this in the Constructor.

Firstly, you cannot spawn actors in the Constructor as SpawnActor requires the world to exist. Also, be sure to check to see if GetWorld is returning null, as this would actually crash if your other If check wasn’t failing.

Secondly, your code class will not see anything set in blueprints in construction, so this If check will fail every time unless it is initialized in code.

Edit: BeginPlay would be an alright area for this to be run. If you need the asset to be spawned before runtime, I believe you can run the SpawnActor function in the OnConstruct function, but I can’t quite remember if that works.

Thank you, this works as expected!