TExcelTAD
Home › Unity with C# › Unity Exercises

Unity Exercises

Time to practise. Unity itself can't run here, so each exercise works on a plain C# model of a Unity mechanism from this course: the same logic you'd put in a MonoBehaviour or a plain class it delegates to. Every starter compiles and runs. Replace the TODO parts, press ▶ Run, and compare your output with the expected output. When you're done, or stuck, open the solution.

Tip: There's always more than one correct solution. If your output matches, your answer is right.

Exercise 1: How many FixedUpdates?

Unity runs FixedUpdate with a 20 ms step and an accumulator. Given the frame times below, print how many fixed steps run in each frame. Expected output:

text
frame 1 (10 ms): 0 fixed steps
frame 2 (25 ms): 1 fixed steps
frame 3 (45 ms): 3 fixed steps
frame 4 (5 ms): 0 fixed steps
frame 5 (16 ms): 1 fixed steps
csharp · try it yourself
using System;

int[] frameMs = { 10, 25, 45, 5, 16 };
const int FixedStepMs = 20;
int accumulator = 0;

for (int f = 0; f < frameMs.Length; f++)
{
    int steps = 0;
    // TODO: add the frame time to the accumulator and count whole fixed steps
    Console.WriteLine(
quot;frame {f + 1} ({frameMs[f]} ms): {steps} fixed steps"); }
frame 1 (10 ms): 0 fixed steps
frame 2 (25 ms): 0 fixed steps
frame 3 (45 ms): 0 fixed steps
frame 4 (5 ms): 0 fixed steps
frame 5 (16 ms): 0 fixed steps
Show solution
csharp
using System;

int[] frameMs = { 10, 25, 45, 5, 16 };
const int FixedStepMs = 20;
int accumulator = 0;

for (int f = 0; f < frameMs.Length; f++)
{
    int steps = 0;
    accumulator += frameMs[f];
    while (accumulator >= FixedStepMs)
    {
        accumulator -= FixedStepMs;
        steps++;
    }
    Console.WriteLine(
quot;frame {f + 1} ({frameMs[f]} ms): {steps} fixed steps"); }

The leftover carries over: 10 (0 steps, 10 left), 35 (1 step, 15 left), 60 (3 steps, 0 left), 5 (0 steps), 21 (1 step, 1 left). A 45 ms frame runs three physics steps, a 5 ms frame none.

Exercise 2: Fake null

Make IsAlive work for destroyed objects. Thing overloads == like UnityEngine.Object. The broken version uses is null. Expected output:

text
coin alive: True
coin alive: False
csharp · try it yourself
using System;

var coin = new Thing();
Console.WriteLine(
quot;coin alive: {IsAlive(coin)}"); coin.Destroy(); Console.WriteLine(
quot;coin alive: {IsAlive(coin)}"); static bool IsAlive(Thing? t) => !(t is null); // TODO: use the overloaded == instead class Thing { bool destroyed; public void Destroy() => destroyed = true; public static bool operator ==(Thing? a, Thing? b) => (a is null || a.destroyed) && (b is null || b.destroyed) || ReferenceEquals(a, b); public static bool operator !=(Thing? a, Thing? b) => !(a == b); public override bool Equals(object? o) => o is Thing t && this == t; public override int GetHashCode() => 0; }
coin alive: True
coin alive: True
Show solution
csharp
static bool IsAlive(Thing? t) => t != null;      // the overloaded != knows about destroyed objects

Exercise 3: A tiny ObjectPool

Finish Get and Release. Get reuses an inactive object if there is one, otherwise creates a new one. Release keeps the object only while the pool holds fewer than maxSize inactive objects. Expected output:

text
got #1, #2, #3
released all, inactive 2, created 3
got #2 again
csharp · try it yourself
using System;
using System.Collections.Generic;

var pool = new Pool(maxSize: 2);
var a = pool.Get(); var b = pool.Get(); var c = pool.Get();
Console.WriteLine(
quot;got #{a.Id}, #{b.Id}, #{c.Id}"); pool.Release(a); pool.Release(b); pool.Release(c); Console.WriteLine(
quot;released all, inactive {pool.Inactive}, created {pool.Created}"); Console.WriteLine(
quot;got #{pool.Get().Id} again"); class Bullet { public int Id; } class Pool { readonly Stack<Bullet> inactive = new(); readonly int maxSize; public int Created; public int Inactive => inactive.Count; public Pool(int maxSize) => this.maxSize = maxSize; public Bullet Get() { // TODO: pop an inactive bullet if there is one return new Bullet { Id = ++Created }; } public void Release(Bullet b) { // TODO: push b only while fewer than maxSize are inactive } }
got #1, #2, #3
released all, inactive 0, created 3
got #4 again
Show solution
csharp
public Bullet Get() => inactive.Count > 0 ? inactive.Pop() : new Bullet { Id = ++Created };

public void Release(Bullet b)
{
    if (inactive.Count < maxSize) inactive.Push(b);
    // else: the real ObjectPool calls actionOnDestroy here
}

#1 and #2 are kept, #3 is dropped because the pool is full, and Get pops the last one pushed: #2.

Exercise 4: Unsubscribe in OnDisable

The Hud subscribes in OnEnable but never unsubscribes, so a disabled HUD still updates. Add the missing OnDisable. Expected output:

text
HUD shows 10
score changed to 20 (nobody listening)
csharp · try it yourself
using System;

var score = new ScoreChannel();
var hud = new Hud(score);
hud.OnEnable();
score.Raise(10);
hud.OnDisable();
score.Raise(20);

class ScoreChannel
{
    public event Action<int>? Changed;
    public void Raise(int v)
    {
        if (Changed == null) Console.WriteLine(
quot;score changed to {v} (nobody listening)"); else Changed(v); } } class Hud { readonly ScoreChannel channel; public Hud(ScoreChannel c) => channel = c; public void OnEnable() => channel.Changed += Show; public void OnDisable() { /* TODO */ } void Show(int v) => Console.WriteLine(
quot;HUD shows {v}"); }
HUD shows 10
HUD shows 20
Show solution
csharp
public void OnDisable() => channel.Changed -= Show;

Exercise 5: Migrate an old save

Version 1 saves stored "hp"; version 2 renamed it to "health" and added "lives" (default 3). Write Migrate so old saves load. Expected output:

text
v1 -> health=70 lives=3 version=2
v2 -> health=55 lives=1 version=2
csharp · try it yourself
using System;
using System.Collections.Generic;

var v1 = new Dictionary<string, int> { ["version"] = 1, ["hp"] = 70 };
var v2 = new Dictionary<string, int> { ["version"] = 2, ["health"] = 55, ["lives"] = 1 };
foreach (var save in new[] { v1, v2 })
{
    string from = 
quot;v{save["version"]}"; Migrate(save); Console.WriteLine(
quot;{from} -> health={save.GetValueOrDefault("health")} lives={save.GetValueOrDefault("lives")} version={save["version"]}"); } static void Migrate(Dictionary<string, int> save) { // TODO: if version is 1, move "hp" to "health", add "lives" = 3, set version to 2 }
v1 -> health=0 lives=0 version=1
v2 -> health=55 lives=1 version=2
Show solution
csharp
static void Migrate(Dictionary<string, int> save)
{
    if (save["version"] == 1)
    {
        save["health"] = save["hp"];
        save.Remove("hp");
        save["lives"] = 3;
        save["version"] = 2;
    }
}

Exercise 6: Add a Stunned state

The guard's machine has Patrol and Chase. Add a Stunned state: when stunned is true the guard goes to Stunned from any state, and after 2 ticks in Stunned it returns to Patrol. Expected output:

text
tick 0: Patrol
tick 1: Chase
tick 2: Stunned
tick 3: Stunned
tick 4: Patrol
tick 5: Chase
csharp · try it yourself
using System;

bool[] seesPlayer = { false, true, true, true, true, true };
bool[] stunned    = { false, false, true, false, false, false };
string state = "Patrol";
int stunTicks = 0;

for (int tick = 0; tick < seesPlayer.Length; tick++)
{
    // TODO: handle "stunned" first (from any state), then count down in Stunned
    if (state == "Patrol" && seesPlayer[tick]) state = "Chase";
    else if (state == "Chase" && !seesPlayer[tick]) state = "Patrol";
    Console.WriteLine(
quot;tick {tick}: {state}"); }
tick 0: Patrol
tick 1: Chase
tick 2: Chase
tick 3: Chase
tick 4: Chase
tick 5: Chase
Show solution
csharp
for (int tick = 0; tick < seesPlayer.Length; tick++)
{
    if (stunned[tick]) { state = "Stunned"; stunTicks = 0; }
    else if (state == "Stunned") { if (++stunTicks >= 2) state = "Patrol"; }
    else if (state == "Patrol" && seesPlayer[tick]) state = "Chase";
    else if (state == "Chase" && !seesPlayer[tick]) state = "Patrol";
    Console.WriteLine(
quot;tick {tick}: {state}"); }

In tick 3 the guard has spent one tick stunned; in tick 4 the second tick ends the stun and it returns to Patrol, even though it can see the player. It notices them again in tick 5.

Test yourself

Fixed step 20 ms, accumulator holds 15 ms, the next frame takes 45 ms. How many FixedUpdates run?

  1. 2
  2. 3
  3. 1
  4. 4

A pool with maxSize 2 receives three releases in a row. What happens to the third object?

  1. It is kept anyway
  2. It is destroyed (actionOnDestroy)
  3. An exception is thrown
  4. It replaces the first