C++ Game Mode Tutorial

C++ Game Mode Tutorial This tutorial will teach you how to make a simple Gun Game mode for UT using C++. We'll be making a UE4 plugin that defines a child class of AUTGameMode. I recommend reading ...

Updated over 4 years ago Edit Page Revisions

C++ Game Mode Tutorial

This tutorial will teach you how to make a simple Gun Game mode for UT using C++. We'll be making a UE4 plugin that defines a child class of AUTGameMode. I recommend reading the C++ Mutator Tutorial, Blueprint_Mutator_Tutorial_-_Instagib and Blueprint_Mutator_Tutorial_-_Low_Grav first. I will be glossing over things covered in depth in other tutorials.

This tutorial is out of date and does not compile in 4.14, working version can be found within Plugins/SampleGameMode

Requirements

  • Engine version: 4.3
  • Skill level: intermediate C++ and blueprint knowledge

Directory Structure

  • If UnrealTournament\Plugins does not already exist, create it
  • Create a directory inside of UnrealTournament\Plugins to hold our game mode, in this case it would be "SampleGameMode"
  • Create "Source" and "Content" directories inside of the SampleGameMode directory
  • Create a "Public" directory and a "Private" directory inside of the last "Source" directory that we made

UPlugin File

  • We need to create SampleGameMode.uplugin to let UE4 know we have a plugin it should load
  • It should live at the same level that the Source directory does
  • The key difference between this .uplugin and the one in the mutator sample is that EnabledByDefault and CanContainContent are set

SampleGameMode.uplugin - Plugin defintion

{
    "FileVersion" : 3,
    
    "FriendlyName" : "Sample Game Mode",
    "Version" : 1,
    "VersionName" : "1.0",
    "CreatedBy" : "Epic Games, Inc.",
    "CreatedByURL" : "http://epicgames.com",
    "EngineVersion" : "4.3.0",
    "Description" : "Sample Game Mode",
    "Category" : "UnrealTournament.GameMode",
    "EnabledByDefault" : true,
    "CanContainContent" : true,
    
    "Modules" :
    [
        {
            "Name" : "SampleGameMode",
            "Type" : "Runtime",
            "WhitelistPlatforms" : [ "Win32", "Win64" ]
        }
    ]
}

Build.cs File

  • We need to create SampleGameMode.Build.cs so that Unreal Build tool knows how to generate our dll file
  • It should live at the same level that the Public and Private directories do
  • We'll use the PrivateIncludesPaths array to make #include cleaner throughout our source files

SampleGameMode.Build.cs - Unreal Build Tool definitions

namespace UnrealBuildTool.Rules
{
    public class SampleGameMode : ModuleRules
    {
        public SampleGameMode(TargetInfo Target)
        {
            PrivateIncludePaths.Add("SampleGameMode/Private");

            PublicDependencyModuleNames.AddRange(
                new string[]
                {
                    "Core",
                    "CoreUObject",
                    "Engine",
                    "UnrealTournament",
                }
                );
        }
    }
}

Header File

  • Unreal Build Tool requires that we have a shared header file as the first include in every cpp source file in the plugin.
  • We'll put the SampleGameMode.h header file inside of the Public directory
    1. include "SampleGameMode.generated.h" is required by Unreal Header Tool
  • Our header is a bit more complex than the mutator one. We've defined two custom structs that we've made BlueprintType so they'll be visible when we're in the editor.
  • You'll notice that each of the structs is just a TArray and their usage in the ASampleGameMode is just a TArray. UE4 does not currently support TArrays of TArrays so we work around that by housing the inner array inside of a structure.
  • We've exposed the StartingInventories and ScoringDamageTypes TArrays to blueprints so they can be filled with content references later. In order for the editor to see them, we made them UPROPERTYs with BlueprintReadWrite markup

SampleGameMode.h - Sample Mutator class definition

// Copyright 1998-2014 Epic Games, Inc. All Rights Reserved.
#pragma once

#include "Core.h"
#include "Engine.h"
#include "UTWeapon.h"
#include "UTGameMode.h"

#include "SampleGameMode.generated.h"

USTRUCT(BlueprintType)
struct FStartingInventory
{
    GENERATED_USTRUCT_BODY()

    UPROPERTY(EditAnywhere, BlueprintReadWrite, Category="GameMode")
    TArray Inventory;
};

USTRUCT(BlueprintType)
struct FDamageTypeToProgess
{
    GENERATED_USTRUCT_BODY()

    UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "GameMode")
    TArray DamageType;
};

UCLASS(Blueprintable, Meta = (ChildCanTick))
class ASampleGameMode : public AUTGameMode
{
    GENERATED_UCLASS_BODY()

    UPROPERTY(EditAnywhere, BlueprintReadWrite, Category="GameMode")
    TArray StartingInventories;

    UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "GameMode")
    TArray ScoringDamageTypes;

    virtual void GiveDefaultInventory(APawn* PlayerPawn) override;
    virtual void ScoreKill(AController* Killer, AController* Other, TSubclassOf DamageType) override;
    virtual void GiveNewGun(AUTCharacter *UTCharacter);
};

Plugin Module Interface

  • Very similar to the mutator sample here, just some name changes

SampleGameModePlugin.cpp - Plugin Module Interface

// Copyright 1998-2014 Epic Games, Inc. All Rights Reserved.

#include "SampleGameMode.h"

#include "Core.h"
#include "Engine.h"
#include "ModuleManager.h"
#include "ModuleInterface.h"

class FSampleGameModePlugin : public IModuleInterface
{
    /** IModuleInterface implementation */
    virtual void StartupModule() override;
    virtual void ShutdownModule() override;
};

IMPLEMENT_MODULE( FSampleGameModePlugin, SampleGameMode )

void FSampleGameModePlugin::StartupModule()
{
    
}

void FSampleGameModePlugin::ShutdownModule()
{
    
}

The Game Mode (C++)

  • Our aim with this tutorial is to make a game mode that functions like "Gun Game", you start with a weapon according to your score and going up in score gives you the next gun in the sequence. Pickups are disabled and so are weapon drops.
  • We'll use C++ to handle giving players the right guns on spawn and giving them the right guns after scoring.
  • We'll use Blueprints to handle disabling weapon drops and pickups.
  • Blueprints will also be used to get content references to weapons and damagetypes as hard coding them in C++ can be brittle.
  • ASampleGameMode::GiveDefaultInventory reads the content reference from StartingInventories that we'll set later in blueprints and spawns that inventory for the spawning player
  • ASampleGameMode::ScoreKill verifies that the killing damage type is equal to the content reference from ScoringDamageTypes and then calls GiveNewGun on the killer
  • ASampleGameMode::GiveNewGun will discard the character's current inventory and give them the proper gun by reading a content reference from StartingInventories

SampleGameMode.cpp

// Copyright 1998-2014 Epic Games, Inc. All Rights Reserved.

#include "SampleGameMode.h"

ASampleGameMode::ASampleGameMode(const FPostConstructInitializeProperties& PCIP)
    : Super(PCIP)
{
}

void ASampleGameMode::GiveDefaultInventory(APawn* PlayerPawn)
{
    // Don't call Super
        
    AUTCharacter* UTCharacter = Cast(PlayerPawn);
    if (UTCharacter != nullptr && UTCharacter->GetInventory() == nullptr)
    {
        int32 InventoryIndex = PlayerPawn->PlayerState->Score;
        if (InventoryIndex >= StartingInventories.Num())
        {
            InventoryIndex = StartingInventories.Num() - 1;
        }
        
        if (StartingInventories.IsValidIndex(InventoryIndex))
        {
            for (int32 i = 0; i < StartingInventories[InventoryIndex].Inventory.Num(); i++)
            {
                if (StartingInventories[InventoryIndex].Inventory[i] != nullptr)
                {
                    UTCharacter->AddInventory(GetWorld()->SpawnActor(StartingInventories[InventoryIndex].Inventory[i], FVector(0.0f), FRotator(0, 0, 0)), true);
                }
            }
        }
    }
}

void ASampleGameMode::ScoreKill(AController* Killer, AController* Other, TSubclassOf DamageType)
{
    // Just a suicide, pass it through
    if (Killer == Other 

 Killer == nullptr)
    {
        Super::ScoreKill(Killer, Other, DamageType);
        return;
    }

    APlayerState* KillerPlayerState = Killer->PlayerState;
    if (KillerPlayerState)
    {
        int32 DamageIndex = KillerPlayerState->Score;
        if (DamageIndex >= ScoringDamageTypes.Num())
        {
            DamageIndex = ScoringDamageTypes.Num() - 1;
        }

        for (int32 i = 0; i < ScoringDamageTypes[DamageIndex].DamageType.Num(); i++)
        {
            if (DamageType == ScoringDamageTypes[DamageIndex].DamageType[i])
            {
                Super::ScoreKill(Killer, Other, DamageType);
                
                // If we changed score, give player a new gun
                if (DamageIndex != KillerPlayerState->Score)
                {
                    AUTCharacter* UTCharacter = Cast(Killer->GetPawn());
                    if (UTCharacter != nullptr)
                    {
                        GiveNewGun(UTCharacter);
                    }
                }

                break;
            }
        }
    }
}

void ASampleGameMode::GiveNewGun(AUTCharacter *UTCharacter)
{
    UTCharacter->DiscardAllInventory();

    int32 InventoryIndex = UTCharacter->PlayerState->Score;
    if (InventoryIndex >= StartingInventories.Num())
    {
        InventoryIndex = StartingInventories.Num() - 1;
    }

    if (StartingInventories.IsValidIndex(InventoryIndex))
    {
        for (int32 i = 0; i < StartingInventories[InventoryIndex].Inventory.Num(); i++)
        {
            if (StartingInventories[InventoryIndex].Inventory[i] != nullptr)
            {
                UTCharacter->AddInventory(GetWorld()->SpawnActor(StartingInventories[InventoryIndex].Inventory[i], FVector(0.0f), FRotator(0, 0, 0)), true);
            }
        }
    }
}

Editor Setup

  • You'll need to enable "Show Plugin Content" in the Content Browser's "View Options" menu

File:Gamemodetutorial_viewplugincontent.png

Mutator Blueprint

File:Gamemodetutorial_mutator.png

Game Mode Blueprint

  • Open up BP_SampleGameMode and go to the default properties tab
  • First, we'll set the Built in Mutators array to reference BP_SampleGameBuiltinMutator

File:Gamemodetutorial_builtin.png

  • Next, we'll set the HUD Class to UTHUD_DM

File:Gamemodetutorial_hudclass.png

  • Third, we'll set up the content references to our guns in the StartingInventories array

File:Gamemodetutorial_startinginventory.png

  • Finally, we'll set up the content references to our damage types in the ScoringDamageTypes array

File:Gamemodetutorial_damagetypes.png

Testing

  • To make typing our command line easier, you should add a game mode alias to DefaultGame.ini
  • Under [/Script/Engine.GameMode] put +GameModeClassAliases=(ShortName="Sample",GameClassName="/SampleGameMode/BP_SampleGameMode.BP_SampleGameMode_C")
  • The game type can now be tested by using ?game=sample instead of ?game=/SampleGameMode/BP_SampleGameMode.BP_SampleGameMode_C
  • Make sure to restart the editor after putting that in the ini
  • I prefer to test in PIE by setting the number of clients to 2, but you can also test via commandline by running a server with "ue4editor unrealtournament -game example_map?game=sample?listen" and a client with "ue4editor unrealtournament -game 127.0.0.1"