Instantiating an Actor using SpawnActor

For this recipe, you'll need to have an Actor subclass ready to instantiate. You can use a built-in class such as StaticMeshActor, but it would help to practice with the custom Actor you made in the previous recipe.

How to do it...

  1. Create a new C++ class, like in the previous recipe. This time, select GameMode as your base class, giving it a name such as UE4CookbookGameMode.
  2. Declare a function override in your new GameMode class:
    virtual void BeginPlay() override;
  3. Implement BeginPlay in the .cpp file:
    void AUE4CookbookGameMode::BeginPlay() { Super::BeginPlay(); GEngine->AddOnScreenDebugMessage(-1, -1, FColor::Red, TEXT("Actor Spawning")); FTransform SpawnLocation; GetWorld()->SpawnActor<AMyFirstActor>( AMyFirstActor::StaticClass(), ...

Get Unreal Engine 4 Scripting with C++ Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.