Skip to content
Tutorials Center
My learning

Topics

Lesson 24 of 38 ยท C++ Gameplay

Delegates, Timers and Spawning in C++

Use delegates, dynamic multicast events, timer handles and SpawnActor in Unreal Engine C++. Build decoupled gameplay code with overlap events and a spawner example.

Gameplay code is mostly reactions: when the player touches a coin, play a sound; when health reaches zero, show a menu; every three seconds, spawn an enemy. Unreal Engine gives you three tools for this: delegates (events), timers and spawning. They let objects cooperate without hard-coding each other's types.

The engine is not available on this site, so the C++ is read-only. Python stand-ins model the delegate and timer mechanics.

Delegates

A delegate is a type-safe function pointer that can be bound at run time. Unreal has several flavours, declared with macros:

Macro Bindings Blueprint use
DECLARE_DELEGATE_OneParam one function no
DECLARE_MULTICAST_DELEGATE_OneParam many functions no
DECLARE_DYNAMIC_MULTICAST_DELEGATE_OneParam many, serializable yes (BlueprintAssignable)

The most useful for gameplay is the dynamic multicast delegate, because designers can bind to it in Blueprints:

C++
DECLARE_DYNAMIC_MULTICAST_DELEGATE_TwoParams(FOnHealthChanged, float, NewHealth, float, Delta);

UCLASS()
class UHealthComponent : public UActorComponent
{
    GENERATED_BODY()

public:
    UPROPERTY(BlueprintAssignable, Category = "Health")
    FOnHealthChanged OnHealthChanged;

    UFUNCTION(BlueprintCallable, Category = "Health")
    void ApplyDamage(float Amount)
    {
        Health = FMath::Max(0.f, Health - Amount);
        OnHealthChanged.Broadcast(Health, -Amount);
    }

private:
    float Health = 100.f;
};

Anyone interested binds a function. For dynamic delegates the target function must be a UFUNCTION:

C++
HealthComp->OnHealthChanged.AddDynamic(this, &AMyHud::HandleHealthChanged);

and unbinds with RemoveDynamic (usually in EndPlay). The health component does not know the HUD exists. That is the point: the broadcaster does not depend on its listeners.

Collision events use the same mechanism. A trigger volume exposes OnComponentBeginOverlap:

C++
void ACoin::BeginPlay()
{
    Super::BeginPlay();
    Sphere->OnComponentBeginOverlap.AddDynamic(this, &ACoin::OnOverlap);
}

void ACoin::OnOverlap(UPrimitiveComponent* Overlapped, AActor* Other,
    UPrimitiveComponent* OtherComp, int32 BodyIndex, bool bFromSweep, const FHitResult& Hit)
{
    if (Other && Other->IsA<ACharacter>())
    {
        Destroy();
    }
}

A model of a multicast delegate

Python Stand-in: multicast delegate

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.

Timers

Never block or spin waiting in gameplay code. Ask the world's timer manager to call you later:

C++
// Header
FTimerHandle SpawnTimer;

// Source: call SpawnEnemy every 3 seconds, starting after 3 seconds
GetWorldTimerManager().SetTimer(SpawnTimer, this, &AEnemySpawner::SpawnEnemy, 3.0f, /*bLoop=*/true);

// Stop it
GetWorldTimerManager().ClearTimer(SpawnTimer);

Pass FirstDelay as a fifth argument if the first call should happen at a different time. Timers survive a frame rate drop: they fire based on game time, and a long frame can trigger a looping timer more than once to catch up. Clear timers in EndPlay, or use the component or Actor's own timer manager, so they do not call into destroyed objects.

For a delay of one frame, prefer GetWorld()->GetTimerManager().SetTimerForNextTick(...).

Python Stand-in: a timer manager driven by game time

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.

Spawning Actors

C++
void AEnemySpawner::SpawnEnemy()
{
    if (!EnemyClass)
    {
        return;
    }

    FActorSpawnParameters Params;
    Params.SpawnCollisionHandlingOverride =
        ESpawnActorCollisionHandlingMethod::AdjustIfPossibleButAlwaysSpawn;

    const FTransform Where = SpawnPoint->GetComponentTransform();
    AEnemy* Enemy = GetWorld()->SpawnActor<AEnemy>(EnemyClass, Where, Params);
    if (Enemy)
    {
        SpawnedEnemies.Add(Enemy);   // TArray<TWeakObjectPtr<AEnemy>>
    }
}

EnemyClass is a TSubclassOf<AEnemy> exposed with EditAnywhere, so a designer can choose a Blueprint subclass. SpawnActor returns nullptr if collision handling refuses the location, so always check. To set values before BeginPlay runs, use SpawnActorDeferred and then FinishSpawning.

Keep spawned Actors in weak pointers or a reflected TArray, never as an unreflected raw list. See Memory and garbage collection.

Common mistakes

  • Binding a non-UFUNCTION to a dynamic delegate. It compiles but never fires.
  • Binding twice. Use AddUniqueDynamic when a function could be registered repeatedly.
  • Forgetting to unbind or clear timers. A timer firing on a destroyed object crashes.
  • Spawning in the constructor. Spawn from BeginPlay or later.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Which delegate type can designers bind to in Blueprints?

    Dynamic multicast delegates are serializable and can be exposed to Blueprints with BlueprintAssignable.
  2. 2. What must a function be to bind with AddDynamic?

    Dynamic delegates bind by function name through reflection, so the target must be a UFUNCTION.
  3. 3. How do you run SpawnEnemy every 3 seconds?

    The timer manager calls your function based on game time without blocking the game thread.
  4. 4. Why check the result of SpawnActor?

    Collision handling or an invalid class can make SpawnActor return nullptr.

Summary

  • Delegates decouple broadcasters from listeners; use dynamic multicast delegates for Blueprint-visible events.
  • Bind with AddDynamic to a UFUNCTION, and unbind in EndPlay.
  • Timers (FTimerHandle, SetTimer) replace waiting loops; clear them when done.
  • SpawnActor with a TSubclassOf creates Actors at run time; always check for nullptr.

Next: Materials and PBR Basics