TExcelTAD
Home › Unreal Engine 5 with C++ › Unreal Exercises

Unreal Exercises

Each exercise is a runnable C++ model of an engine mechanism from this course, with one piece missing. Replace the TODO, press ▶ Run, and compare with the expected output. The output block under each starter shows what the unfinished starter prints. Each exercise also has a short In the engine note that tells you where the same idea lives in real Unreal code.

# Exercise Practises Lesson
1 Make the GC see the reference mark and sweep, UPROPERTY Garbage Collection
2 RemoveAll for a multicast delegate delegates, unbinding in EndPlay Delegates
3 Tag queries hierarchical matching Gameplay Tags
4 Override and Divide modifiers GAS aggregation GAS: Attributes & Effects
5 Validate a Server RPC authority, never trusting the client RPCs & Authority
6 A cooldown decorator behavior trees Behavior Trees

Exercise 1: Make the GC see the reference

The weapon holds its ammo-counter object only through Raw, so the collector frees it. Make the reference traced: add it to the weapon's UProperties list, the way UPROPERTY() registers a member, so the counter survives both GC passes.

cpp · try it yourself
#include <iostream>
#include <string>
#include <vector>

struct Object { std::string Name; bool Alive = true, Marked = false; std::vector<Object*> UProperties; Object* Raw = nullptr; };

void Mark(Object* o) {
    if (!o || !o->Alive || o->Marked) return;
    o->Marked = true;
    for (Object* r : o->UProperties) Mark(r);
}

void GC(std::vector<Object*>& heap, Object* root, int pass) {
    for (Object* o : heap) o->Marked = false;
    Mark(root);
    std::cout << "GC pass " << pass << ":";
    for (Object* o : heap)
        if (o->Alive && !o->Marked) { o->Alive = false; std::cout << " freed " << o->Name; }
    std::cout << "\n";
}

int main() {
    Object level{"Level"}, weapon{"Weapon"}, counter{"AmmoCounter"};
    std::vector<Object*> heap = {&level, &weapon, &counter};
    level.UProperties.push_back(&weapon);
    weapon.Raw = &counter;
    // TODO: make the weapon's reference to the counter visible to the GC

    GC(heap, &level, 1);
    GC(heap, &level, 2);
    std::cout << "AmmoCounter alive: " << (counter.Alive ? "yes" : "no") << "\n";
}
GC pass 1: freed AmmoCounter
GC pass 2:
AmmoCounter alive: no

Expected output when solved:

text
GC pass 1:
GC pass 2:
AmmoCounter alive: yes

In the engine: UPROPERTY() TObjectPtr<UAmmoCounter> AmmoCounter; in the weapon's header.

Show solution

Replace the TODO line with:

cpp
weapon.UProperties.push_back(&counter);

Exercise 2: RemoveAll for a multicast delegate

A HUD widget is closed, and in its EndPlay it calls OnHealthChanged.RemoveAll(this) to remove every binding it owns. Implement RemoveAll(owner) so the second broadcast reaches only the sound system.

cpp · try it yourself
#include <functional>
#include <iostream>
#include <string>
#include <vector>

struct Delegate {
    struct Binding { const void* Owner; std::function<void(int)> Fn; };
    std::vector<Binding> Bindings;
    void Add(const void* owner, std::function<void(int)> fn) { Bindings.push_back({owner, std::move(fn)}); }
    void RemoveAll(const void* owner) {
        // TODO: remove every binding whose Owner is `owner`
        (void)owner;
    }
    void Broadcast(int v) { for (auto& b : Bindings) b.Fn(v); }
};

int main() {
    Delegate OnHealthChanged;
    int hud = 0, sound = 0;                       // their addresses stand in for `this`
    OnHealthChanged.Add(&hud, [](int h) { std::cout << "  HUD bar: " << h << "\n"; });
    OnHealthChanged.Add(&hud, [](int h) { std::cout << "  HUD low-health vignette: " << (h < 30 ? "on" : "off") << "\n"; });
    OnHealthChanged.Add(&sound, [](int h) { std::cout << "  Sound: heartbeat " << (h < 30 ? "fast" : "calm") << "\n"; });

    std::cout << "hit:\n";
    OnHealthChanged.Broadcast(55);
    OnHealthChanged.RemoveAll(&hud);
    std::cout << "HUD closed, hit:\n";
    OnHealthChanged.Broadcast(20);
}
hit:
  HUD bar: 55
  HUD low-health vignette: off
  Sound: heartbeat calm
HUD closed, hit:
  HUD bar: 20
  HUD low-health vignette: on
  Sound: heartbeat fast

Expected output when solved:

text
hit:
  HUD bar: 55
  HUD low-health vignette: off
  Sound: heartbeat calm
HUD closed, hit:
  Sound: heartbeat fast

In the engine: Health->OnHealthChanged.RemoveAll(this); in EndPlay, or RemoveDynamic for each dynamic binding.

Show solution
cpp
void RemoveAll(const void* owner) {
    std::erase_if(Bindings, [owner](const Binding& b) { return b.Owner == owner; });
}

Exercise 3: Tag queries

MatchesTag currently compares strings exactly, so the hierarchical checks fail. Make MatchesTag(a, b) true when a equals b or a is a child of b (it starts with b followed by a .). Status.Deb must still not match Status.Debuff.

cpp · try it yourself
#include <iostream>
#include <string>
#include <vector>

bool MatchesTag(const std::string& a, const std::string& b) {
    // TODO: hierarchical match: a == b, or a starts with b + "."
    return a == b;
}

bool HasTag(const std::vector<std::string>& container, const std::string& t) {
    for (const auto& x : container) if (MatchesTag(x, t)) return true;
    return false;
}

int main() {
    std::vector<std::string> owned = {"Status.Debuff.Burning", "Team.Blue"};
    for (std::string q : {"Status.Debuff.Burning", "Status.Debuff", "Status", "Status.Deb", "Team.Blue.Captain"})
        std::cout << "HasTag(" << q << ") = " << (HasTag(owned, q) ? "true" : "false") << "\n";
}
HasTag(Status.Debuff.Burning) = true
HasTag(Status.Debuff) = false
HasTag(Status) = false
HasTag(Status.Deb) = false
HasTag(Team.Blue.Captain) = false

Expected output when solved:

text
HasTag(Status.Debuff.Burning) = true
HasTag(Status.Debuff) = true
HasTag(Status) = true
HasTag(Status.Deb) = false
HasTag(Team.Blue.Captain) = false

In the engine: FGameplayTagContainer::HasTag does this with precomputed parent tags.

Show solution
cpp
bool MatchesTag(const std::string& a, const std::string& b) {
    return a == b || (a.size() > b.size() && a.compare(0, b.size(), b) == 0 && a[b.size()] == '.');
}

Exercise 4: Override and Divide modifiers

Extend the aggregator so it handles all four operations with GAS's default formula: (Base + ΣAdd) × (1 + Σ(Multiply − 1)) / (1 + Σ(Divide − 1)), except that an Override modifier, if present, replaces the result entirely (use the last one).

cpp · try it yourself
#include <iostream>
#include <iomanip>
#include <string>
#include <vector>

enum class Op { Add, Multiply, Divide, Override };
struct Mod { Op Operation; double Magnitude; };

double Evaluate(double base, const std::vector<Mod>& mods) {
    double add = 0, mul = 0;
    for (const Mod& m : mods) {
        if (m.Operation == Op::Add) add += m.Magnitude;
        if (m.Operation == Op::Multiply) mul += m.Magnitude - 1;
        // TODO: Divide (summed like Multiply) and Override (replaces the result)
    }
    return (base + add) * (1 + mul);
}

int main() {
    std::cout << std::fixed << std::setprecision(1);
    std::cout << "haste x1.5:            " << Evaluate(600, {{Op::Multiply, 1.5}}) << "\n";
    std::cout << "+100, slow /2:         " << Evaluate(600, {{Op::Add, 100}, {Op::Divide, 2}}) << "\n";
    std::cout << "haste + rooted (=0):   " << Evaluate(600, {{Op::Multiply, 1.5}, {Op::Override, 0}}) << "\n";
}
haste x1.5:            900.0
+100, slow /2:         700.0
haste + rooted (=0):   900.0

Expected output when solved:

text
haste x1.5:            900.0
+100, slow /2:         350.0
haste + rooted (=0):   0.0

In the engine: a GE_Rooted duration effect with an Override modifier on MoveSpeed set to 0.

Show solution
cpp
double Evaluate(double base, const std::vector<Mod>& mods) {
    double add = 0, mul = 0, div = 0;
    bool hasOverride = false;
    double overrideValue = 0;
    for (const Mod& m : mods) {
        if (m.Operation == Op::Add) add += m.Magnitude;
        if (m.Operation == Op::Multiply) mul += m.Magnitude - 1;
        if (m.Operation == Op::Divide) div += m.Magnitude - 1;
        if (m.Operation == Op::Override) { hasOverride = true; overrideValue = m.Magnitude; }
    }
    if (hasOverride) return overrideValue;
    return (base + add) * (1 + mul) / (1 + div);
}

Exercise 5: Validate a Server RPC

ServerFire_Implementation trusts whatever the client sends. Add the server-side checks: the shooter must be alive, the weapon must be off cooldown (0.25 s between shots, measured with the server's clock), and the shot origin must be within 200 units of the shooter. Rejected shots print the reason.

cpp · try it yourself
#include <cmath>
#include <iostream>
#include <iomanip>
#include <string>

struct Shooter { double X = 0, Y = 0; bool Alive = true; double LastFireTime = -1; };

void ServerFire_Implementation(Shooter& s, double serverTime, double originX, double originY) {
    std::cout << "t=" << serverTime << " ServerFire from (" << originX << ", " << originY << "): ";
    // TODO: reject if dead, if fired less than 0.25 s ago, or if the origin is more than 200 from the shooter
    s.LastFireTime = serverTime;
    std::cout << "accepted\n";
}

int main() {
    std::cout << std::fixed << std::setprecision(2);
    Shooter s;
    ServerFire_Implementation(s, 1.00, 10, 0);
    ServerFire_Implementation(s, 1.10, 10, 0);     // rapid-fire hack
    ServerFire_Implementation(s, 1.40, 900, 0);    // shooting from across the map
    ServerFire_Implementation(s, 1.60, 20, 5);
    s.Alive = false;
    ServerFire_Implementation(s, 2.00, 0, 0);
}
t=1.00 ServerFire from (10.00, 0.00): accepted
t=1.10 ServerFire from (10.00, 0.00): accepted
t=1.40 ServerFire from (900.00, 0.00): accepted
t=1.60 ServerFire from (20.00, 5.00): accepted
t=2.00 ServerFire from (0.00, 0.00): accepted

Expected output when solved:

text
t=1.00 ServerFire from (10.00, 0.00): accepted
t=1.10 ServerFire from (10.00, 0.00): rejected (cooldown)
t=1.40 ServerFire from (900.00, 0.00): rejected (origin too far)
t=1.60 ServerFire from (20.00, 5.00): accepted
t=2.00 ServerFire from (0.00, 0.00): rejected (dead)

In the engine: these checks go in ServerFire_Implementation, not in _Validate, because failing _Validate disconnects the player. Lag and packet bunching can make honest clients trip a strict cooldown, so real games allow a small tolerance.

Show solution
cpp
void ServerFire_Implementation(Shooter& s, double serverTime, double originX, double originY) {
    std::cout << "t=" << serverTime << " ServerFire from (" << originX << ", " << originY << "): ";
    if (!s.Alive) { std::cout << "rejected (dead)\n"; return; }
    if (s.LastFireTime >= 0 && serverTime - s.LastFireTime < 0.25 - 1e-9) { std::cout << "rejected (cooldown)\n"; return; }
    if (std::hypot(originX - s.X, originY - s.Y) > 200) { std::cout << "rejected (origin too far)\n"; return; }
    s.LastFireTime = serverTime;
    std::cout << "accepted\n";
}

Exercise 6: A cooldown decorator

The enemy should use its Taunt branch at most once every 3 seconds, and otherwise fall through to Chase. Implement the Cooldown decorator: CanEnter returns false while less than Cooldown seconds have passed since the branch last finished (the first time it may always run), and OnFinished records the time.

cpp · try it yourself
#include <iostream>
#include <iomanip>

struct CooldownDecorator {
    double Cooldown = 3.0;
    double LastFinished = -1;
    bool CanEnter(double now) const {
        // TODO: false if the branch finished less than Cooldown seconds ago
        (void)now;
        return true;
    }
    void OnFinished(double now) { LastFinished = now; }
};

int main() {
    std::cout << std::fixed << std::setprecision(1);
    CooldownDecorator taunt;
    for (double t = 0; t <= 7.01; t += 1.0) {           // the tree is evaluated once per second
        if (taunt.CanEnter(t)) {
            std::cout << "t=" << t << " Taunt (1 s)\n";
            taunt.OnFinished(t + 1.0);                    // the taunt animation lasts 1 s
            t += 1.0;                                     // the branch occupies the next second
        } else {
            std::cout << "t=" << t << " Chase\n";
        }
    }
}
t=0.0 Taunt (1 s)
t=2.0 Taunt (1 s)
t=4.0 Taunt (1 s)
t=6.0 Taunt (1 s)

Expected output when solved:

text
t=0.0 Taunt (1 s)
t=2.0 Chase
t=3.0 Chase
t=4.0 Taunt (1 s)
t=6.0 Chase
t=7.0 Chase

In the engine: the built-in Cooldown decorator on the Taunt sequence, with Cool Down Time = 3. It starts counting when the branch finishes, as here.

Show solution
cpp
bool CanEnter(double now) const {
    return LastFinished < 0 || now - LastFinished >= Cooldown - 1e-9;
}

Test yourself

In Exercise 5, why do the checks go in _Implementation rather than _Validate?

  1. _Validate can't read member variables
  2. A failed _Validate disconnects the client; ordinary gameplay rejections should just ignore the request
  3. _Implementation runs first
  4. _Validate only runs on clients

In Exercise 4, what does an Override modifier do in GAS's default aggregation?

  1. Adds to the base
  2. Replaces the final value regardless of other modifiers
  3. Multiplies the result
  4. Is ignored when other modifiers exist