Skip to content
Tutorials Center
My learning

Topics

Lesson 36 of 38 ยท Projects and Practice

Project: A Collectible Coin Game

Build a small coin-collecting game in Unreal Engine with C++. Coin actor, overlap events, score in the game mode, a HUD hook, a timer and a win condition, step by step.

Time to combine what you have learned. In this project you build a small game: a third-person character runs around a level and collects coins before a timer runs out. It uses C++ Actors and components, overlap events, a game mode for rules, delegates to update the interface, and Blueprints for the content.

The Unreal Editor is not available on this site, so the steps below are exact descriptions to follow in your own editor, the C++ is read-only, and the Python stand-ins let you test the rules (scoring, timer, win and lose) before you build them. Written for Unreal Engine 5.x with the Third Person template.

Step 0: set up

  1. Create a project: Games > Third Person, C++, Starter Content off, name it CoinRush.
  2. Open the generated solution in your IDE and build once.
  3. Confirm the template map plays with the mannequin character.

Step 1: the coin

Create a C++ class Actor named CoinPickup (see Your first C++ Actor class).

C++
// CoinPickup.h
UCLASS()
class COINRUSH_API ACoinPickup : public AActor
{
    GENERATED_BODY()

public:
    ACoinPickup();

    UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "Coin")
    int32 Value = 1;

protected:
    virtual void BeginPlay() override;
    virtual void Tick(float DeltaTime) override;

    UPROPERTY(VisibleAnywhere)
    TObjectPtr<USphereComponent> Trigger;

    UPROPERTY(VisibleAnywhere)
    TObjectPtr<UStaticMeshComponent> Mesh;

    UFUNCTION()
    void OnOverlap(UPrimitiveComponent* Comp, AActor* Other, UPrimitiveComponent* OtherComp,
                   int32 BodyIndex, bool bFromSweep, const FHitResult& Hit);
};
C++
// CoinPickup.cpp
ACoinPickup::ACoinPickup()
{
    PrimaryActorTick.bCanEverTick = true;

    Trigger = CreateDefaultSubobject<USphereComponent>(TEXT("Trigger"));
    SetRootComponent(Trigger);
    Trigger->SetSphereRadius(60.f);
    Trigger->SetCollisionProfileName(TEXT("OverlapOnlyPawn"));

    Mesh = CreateDefaultSubobject<UStaticMeshComponent>(TEXT("Mesh"));
    Mesh->SetupAttachment(Trigger);
    Mesh->SetCollisionEnabled(ECollisionEnabled::NoCollision);
}

void ACoinPickup::BeginPlay()
{
    Super::BeginPlay();
    Trigger->OnComponentBeginOverlap.AddDynamic(this, &ACoinPickup::OnOverlap);
}

void ACoinPickup::Tick(float DeltaTime)
{
    Super::Tick(DeltaTime);
    AddActorLocalRotation(FRotator(0.f, 120.f * DeltaTime, 0.f));
}

void ACoinPickup::OnOverlap(UPrimitiveComponent*, AActor* Other, UPrimitiveComponent*, int32, bool, const FHitResult&)
{
    if (ACharacter* Character = Cast<ACharacter>(Other))
    {
        if (ACoinRushGameMode* GM = GetWorld()->GetAuthGameMode<ACoinRushGameMode>())
        {
            GM->AddCoins(Value);
        }
        Destroy();
    }
}

The collision profile OverlapOnlyPawn exists in the default engine presets. Include Components/SphereComponent.h and GameFramework/Character.h. Build, then create a Blueprint subclass BP_Coin and assign a cylinder or any static mesh to the Mesh component, scaled flat like a coin.

Step 2: the rules in the game mode

Create a Game Mode Base class CoinRushGameMode. The game mode owns the rules and is the only place that knows the score and time:

C++
DECLARE_DYNAMIC_MULTICAST_DELEGATE_TwoParams(FOnScoreChanged, int32, Collected, int32, Total);
DECLARE_DYNAMIC_MULTICAST_DELEGATE_OneParam(FOnGameFinished, bool, bWon);

UCLASS()
class ACoinRushGameMode : public AGameModeBase
{
    GENERATED_BODY()

public:
    UPROPERTY(BlueprintAssignable) FOnScoreChanged OnScoreChanged;
    UPROPERTY(BlueprintAssignable) FOnGameFinished OnGameFinished;

    UPROPERTY(EditDefaultsOnly, Category = "Rules")
    float TimeLimit = 60.f;

    UFUNCTION(BlueprintCallable)
    void AddCoins(int32 Amount);

    UFUNCTION(BlueprintPure)
    float GetTimeRemaining() const;

protected:
    virtual void BeginPlay() override;

private:
    int32 Collected = 0;
    int32 TotalCoins = 0;
    bool bFinished = false;
    FTimerHandle EndTimer;
    void Finish(bool bWon);
};

In BeginPlay, count coins with UGameplayStatics::GetAllActorsOfClass(this, ACoinPickup::StaticClass(), Found) (this is acceptable once at startup), store TotalCoins, and start GetWorldTimerManager().SetTimer(EndTimer, [this]{ Finish(false); }, TimeLimit, false). In AddCoins, add to Collected, broadcast OnScoreChanged, and when Collected >= TotalCoins call Finish(true). Finish ignores repeat calls with the bFinished flag, clears the timer, broadcasts OnGameFinished and optionally pauses the game.

Set the project's default game mode in Project Settings > Maps and Modes or in the level's World Settings.

The rules as a testable model

Before wiring a HUD, make sure the rules behave. This stand-in is a Python model of the game mode, including the edge cases that bite in the real one (double-finish, a late coin after the timer ends).

Python Stand-in: game mode rules

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Step 3: show the score

Create a Widget Blueprint WBP_HUD (User Interface > Widget Blueprint) with two Text blocks (ScoreText, TimeText). In the player character or the Level Blueprint, on BeginPlay: Create Widget (WBP_HUD), Add to Viewport, get the game mode, cast to CoinRushGameMode, and Bind Event to OnScoreChanged to update ScoreText with a Format Text node ( / {1}). Bind OnGameFinished to show a "You win" or "Time up" message. For the time display, update TimeText using the widget's Event Tick reading GetTimeRemaining, or a 0.1-second timer (cheaper than every frame).

HUD in C++ is also possible with UUserWidget subclasses and meta = (BindWidget); the Blueprint approach is faster for layout. Keep the rules in C++ and the presentation in Blueprint, which is exactly the split described in the earlier lessons.

Step 4: build the level

  1. Place a few dozen BP_Coin Actors along platforms and corridors. Use the Snap to Floor (End key) so they sit on the ground.
  2. Scatter them with variety: some easy, some reward exploring.
  3. Add a Nav Mesh only if you add AI later.
  4. Add a Directional Light, Sky Atmosphere and Sky Light for a pleasant look (see Lighting).
  5. Test with Play > Selected Viewport, then in Standalone Game mode.

Expansion ideas

  • Coins with different values and colors via a Material Instance Dynamic parameter (see Material instances and parameters).
  • A pickup sound and particle effect played in OnOverlap.
  • A high score saved with USaveGame and UGameplayStatics::SaveGameToSlot.
  • A moving platform and a pit that resets the player (a trigger volume that calls RestartPlayer).
  • Package a Development build and share it with a friend (see Packaging and build configurations).

Common mistakes

  • The coin never triggers. Check the collision profile on the sphere (it must overlap Pawn) and that Generate Overlap Events is on for the character's capsule.
  • Cast fails. The level may use another game mode; set the game mode in World Settings.
  • Score counts twice. The overlap can fire for several components of the character; test Cast<ACharacter> on the actor and destroy at once, as shown.
  • Timer keeps running after the win. Clear it in Finish.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Where should the score and timer rules live in this project?

    The game mode owns the rules of the match; coins just report that they were collected.
  2. 2. Why broadcast delegates from the game mode instead of letting the game mode edit the HUD?

    Listeners bind to the event; the game mode does not need to know the HUD exists.
  3. 3. What bug does the bFinished flag prevent?

    Finish can be reached from the timer and from a coin; the flag ensures only the first result counts.
  4. 4. A coin does not react when the player touches it. What is the best first check?

    Overlap needs compatible collision responses and enabled overlap events on both sides.

Summary

  • A Coin Actor with a sphere trigger reports pickups to the Game Mode.
  • The Game Mode holds the rules (score, timer, win and lose) and broadcasts events.
  • A Widget Blueprint listens to those events and shows the result.
  • Testing rules in a small model first catches edge cases like late events.

Next: Project: A Patrolling Enemy