- Create a new C++ class, like in the previous recipe. This time, select Game Mode Base as your base class:
- Once you have clicked Next, give the new class a name, such as UE4CookbookGameModeBase.
- Declare a function override in the .h file of your new GameModeBase class:
#pragma once
#include "CoreMinimal.h"
#include "GameFramework/GameModeBase.h"
#include "UECookbookGameModeBase.generated.h"
/**
*
*/
UCLASS()
class CHAPTER_04_API AUECookbookGameModeBase : public AGameModeBase
{
GENERATED_BODY()
public:
virtual void BeginPlay() override;
};
- Implement the BeginPlay function in the .cpp file:
#include "UECookbookGameModeBase.h"
#include "MyFirstActor.h" // AMyFirstActor
void AUECookbookGameModeBase::BeginPlay()
{
// Call the parent class version of this function
Super::BeginPlay();
// Displays a red message on the screen for 10 seconds
GEngine->AddOnScreenDebugMessage(-1, 10, FColor::Red,
TEXT("Actor Spawning"));
// Spawn an instance of the AMyFirstActor class at the
//default location.
FTransform SpawnLocation;
GetWorld()->SpawnActor<AMyFirstActor>
(AMyFirstActor::StaticClass(),
SpawnLocation);
}
- Compile your code, either through Visual Studio or by clicking on the Compile button in Unreal Editor:
- Open the World Settings panel for the current level by clicking on the Settings toolbar icon, and then pick World Settings from the drop-down menu:
- In the GameMode Override section, change the game mode to the GameMode subclass you just created:
Setting the GameMode Override property
- Start the level and verify that GameMode spawns a copy of your Actor in the world by looking at the World Outliner panel. You can verify that the BeginPlay function is being run by viewing the Actor Spawning text being displayed on screen. If it doesn't spawn, make sure that there are no obstructions at the world origin to prevent the Actor from being spawned. You can search the list of objects in the world by typing in the search bar at the top of the World Outliner panel. This will filter the entities that are shown: