Mini Project: Crystal Run
Crystal Run is a small 3D collect-and-escape game that uses most of this course. The player runs through a greyboxed level, collects every crystal while patrolling drones try to knock them out, and escapes through a gate that opens once the last crystal is taken, all before the timer runs out. The best time is saved to a JSON file.
| Step | Adds | Lessons used |
|---|---|---|
| 1 | project, folders, greybox level | Editor, ProBuilder |
| 2 | player movement and camera | Input System, CharacterController, Cinemachine |
| 3 | level data and event channels | ScriptableObjects, Event Channels |
| 4 | crystals and the game session (state machine, timer) | Colliders & Triggers, State Machines |
| 5 | the exit gate (async animation) | Awaitable |
| 6 | drones, damage, checkpoints | NavMesh, Events |
| 7 | HUD, audio, best-time save | UI Toolkit, Audio, Save & Load |
| 8 | the rules as a runnable model, then a build | Builds |
You'll write about ten small scripts. Each is complete; paste them into Assets/_Game/Scripts/ as you go.
Step 1: Project and greybox
- In Unity Hub, create a Universal 3D project named
CrystalRunwith a Unity 6 LTS editor. - Set up Git before anything else:
.gitignore,.gitattributes, LFS (setup). Commit. - Create folders:
Assets/_Game/Scenes,Scripts,Prefabs,Data,Materials,Audio,UI. - Install ProBuilder, Cinemachine and AI Navigation from the Package Manager (Input System is already in the template).
- Create the scene
Assets/_Game/Scenes/Level1.unity. With ProBuilder (Tools > ProBuilder > ProBuilder Window, New Shape), build a floor, a few rooms with walls and ramps, and an exit corridor. Keep it ugly; you're testing gameplay. - Create layers
Player,Hazard,Pickup,Walls. Set the walls' layer toWalls.
Step 2: Player and camera
Add a capsule named Player with a CharacterController, tag it Player, put it on the Player layer, and add this script. It's the controller from the CharacterController lesson, trimmed, plus a Teleport method used for respawns.
using UnityEngine;
using UnityEngine.InputSystem;
[RequireComponent(typeof(CharacterController))]
public class PlayerMover : MonoBehaviour
{
[SerializeField] Transform cameraTransform;
[SerializeField] float speed = 7f, jumpHeight = 1.3f, gravity = -25f, coyoteTime = 0.1f;
CharacterController controller;
InputAction move, jump;
float verticalVelocity, lastGrounded = -10f;
public bool InputEnabled { get; set; } = true;
void Awake()
{
controller = GetComponent<CharacterController>();
move = InputSystem.actions.FindAction("Move");
jump = InputSystem.actions.FindAction("Jump");
}
void Update()
{
Vector2 input = InputEnabled ? move.ReadValue<Vector2>() : Vector2.zero;
Vector3 forward = Vector3.ProjectOnPlane(cameraTransform.forward, Vector3.up).normalized;
Vector3 right = Vector3.ProjectOnPlane(cameraTransform.right, Vector3.up).normalized;
Vector3 horizontal = (forward * input.y + right * input.x) * speed;
if (controller.isGrounded)
{
lastGrounded = Time.time;
if (verticalVelocity < 0f) verticalVelocity = -2f;
}
if (InputEnabled && jump.WasPressedThisFrame() && Time.time - lastGrounded <= coyoteTime)
{
verticalVelocity = Mathf.Sqrt(jumpHeight * -2f * gravity);
lastGrounded = -10f;
}
verticalVelocity += gravity * Time.deltaTime;
controller.Move((horizontal + Vector3.up * verticalVelocity) * Time.deltaTime);
if (horizontal.sqrMagnitude > 0.01f)
transform.rotation = Quaternion.Slerp(transform.rotation, Quaternion.LookRotation(horizontal), 15f * Time.deltaTime);
}
public void Teleport(Vector3 position)
{
controller.enabled = false; // a CharacterController overrides transform changes while enabled
transform.position = position;
controller.enabled = true;
verticalVelocity = 0f;
}
}Camera: GameObject > Cinemachine > Cinemachine Camera, set its Tracking Target to the player, add Orbital Follow (position) and Rotation Composer (aim), plus a Cinemachine Input Axis Controller so the mouse or right stick orbits it, and a Deoccluder against the Walls layer. Drag the Main Camera into cameraTransform. Press Play and run around.
Step 3: Level data and event channels
using UnityEngine;
[CreateAssetMenu(menuName = "Crystal Run/Level Definition")]
public class LevelDefinition : ScriptableObject
{
[SerializeField] string levelId = "level1";
[SerializeField, Min(1)] int crystalsRequired = 8;
[SerializeField, Min(10f)] float timeLimit = 180f;
[SerializeField, Min(1)] int lives = 3;
public string LevelId => levelId;
public int CrystalsRequired => crystalsRequired;
public float TimeLimit => timeLimit;
public int Lives => lives;
}using System;
using UnityEngine;
[CreateAssetMenu(menuName = "Crystal Run/Event Channel")]
public class EventChannel : ScriptableObject
{
public event Action Raised;
public void Raise() => Raised?.Invoke();
}Create the assets: Data/Level1.asset (Level Definition), and event channels CrystalCollected, PlayerHit, GateOpened, LevelWon, LevelLost.
Step 4: Crystals and the game session
A crystal is a small mesh with a SphereCollider set to Is Trigger, on the Pickup layer. Make it a prefab and place more than crystalsRequired of them.
using UnityEngine;
public class Crystal : MonoBehaviour
{
[SerializeField] EventChannel crystalCollected;
[SerializeField] float spinSpeed = 90f;
void Update() => transform.Rotate(0f, spinSpeed * Time.deltaTime, 0f);
void OnTriggerEnter(Collider other)
{
if (!other.CompareTag("Player")) return;
crystalCollected.Raise();
gameObject.SetActive(false); // cheaper than Destroy, and easy to reset
}
}The session owns the rules: a small state machine (Playing, Won, Lost), the timer, crystal count and lives.
using System;
using UnityEngine;
public class GameSession : MonoBehaviour
{
public enum State { Playing, Won, Lost }
[SerializeField] LevelDefinition level;
[SerializeField] EventChannel crystalCollected, playerHit, gateOpened, levelWon, levelLost;
public State Current { get; private set; } = State.Playing;
public int Crystals { get; private set; }
public int Lives { get; private set; }
public float TimeLeft { get; private set; }
public LevelDefinition Level => level;
public event Action Changed; // for the HUD
void Awake()
{
Lives = level.Lives;
TimeLeft = level.TimeLimit;
}
void OnEnable()
{
crystalCollected.Raised += OnCrystal;
playerHit.Raised += OnHit;
}
void OnDisable()
{
crystalCollected.Raised -= OnCrystal;
playerHit.Raised -= OnHit;
}
void Update()
{
if (Current != State.Playing) return;
TimeLeft = Mathf.Max(0f, TimeLeft - Time.deltaTime);
if (TimeLeft == 0f) Lose();
Changed?.Invoke();
}
void OnCrystal()
{
if (Current != State.Playing) return;
Crystals++;
if (Crystals == level.CrystalsRequired) gateOpened.Raise();
Changed?.Invoke();
}
void OnHit()
{
if (Current != State.Playing) return;
Lives--;
if (Lives <= 0) Lose();
Changed?.Invoke();
}
public void ReachExit()
{
if (Current != State.Playing || Crystals < level.CrystalsRequired) return;
Current = State.Won;
levelWon.Raise();
Changed?.Invoke();
}
void Lose()
{
Current = State.Lost;
levelLost.Raise();
}
}Step 5: The exit gate
The gate is a wall that slides into the floor when GateOpened is raised. Behind it, an ExitZone trigger tells the session that the player escaped.
using System;
using UnityEngine;
public class ExitGate : MonoBehaviour
{
[SerializeField] EventChannel gateOpened;
[SerializeField] Transform door;
[SerializeField] float sinkDepth = 4f, duration = 1.5f;
void OnEnable() => gateOpened.Raised += Open;
void OnDisable() => gateOpened.Raised -= Open;
async void Open()
{
try
{
Vector3 start = door.localPosition, end = start + Vector3.down * sinkDepth;
for (float t = 0f; t < duration; t += Time.deltaTime)
{
door.localPosition = Vector3.Lerp(start, end, Mathf.SmoothStep(0f, 1f, t / duration));
await Awaitable.NextFrameAsync(destroyCancellationToken);
}
door.localPosition = end;
}
catch (OperationCanceledException) { } // the level was unloaded mid-animation
}
}
public class ExitZone : MonoBehaviour // trigger collider behind the gate
{
[SerializeField] GameSession session;
void OnTriggerEnter(Collider other)
{
if (other.CompareTag("Player")) session.ReachExit();
}
}Step 6: Drones, damage and checkpoints
- Add a NavMesh Surface to the level root and Bake.
- A drone is a sphere with a NavMeshAgent, a trigger collider slightly bigger than its mesh, on the
Hazardlayer. It patrols waypoints and chases the player when it sees them, a two-state machine like the guard.
using UnityEngine;
using UnityEngine.AI;
[RequireComponent(typeof(NavMeshAgent))]
public class Drone : MonoBehaviour
{
[SerializeField] Transform[] waypoints;
[SerializeField] float sightRange = 8f, loseRange = 11f; // hysteresis
[SerializeField] LayerMask wallMask;
[SerializeField] EventChannel playerHit;
NavMeshAgent agent;
Transform player;
int waypoint;
bool chasing;
float hitCooldownUntil;
void Awake() => agent = GetComponent<NavMeshAgent>();
void Start()
{
player = GameObject.FindWithTag("Player").transform; // once, at startup: fine
agent.SetDestination(waypoints[0].position);
}
void Update()
{
float distance = Vector3.Distance(transform.position, player.position);
bool visible = !Physics.Linecast(transform.position, player.position + Vector3.up, wallMask);
if (!chasing && distance < sightRange && visible) { chasing = true; agent.speed = 5f; }
else if (chasing && (distance > loseRange || !visible)) { chasing = false; agent.speed = 3f; }
if (chasing) agent.SetDestination(player.position);
else if (!agent.pathPending && agent.remainingDistance < 0.5f)
{
waypoint = (waypoint + 1) % waypoints.Length;
agent.SetDestination(waypoints[waypoint].position);
}
}
void OnTriggerEnter(Collider other)
{
if (!other.CompareTag("Player") || Time.time < hitCooldownUntil) return;
hitCooldownUntil = Time.time + 1f;
playerHit.Raise();
}
}Checkpoints are trigger volumes; the player respawns at the last one touched when hit:
using UnityEngine;
public class PlayerRespawn : MonoBehaviour
{
[SerializeField] EventChannel playerHit;
[SerializeField] PlayerMover mover;
Vector3 checkpoint;
void Awake() => checkpoint = transform.position;
void OnEnable() => playerHit.Raised += Respawn;
void OnDisable() => playerHit.Raised -= Respawn;
public void SetCheckpoint(Vector3 position) => checkpoint = position;
void Respawn() => mover.Teleport(checkpoint);
}
public class Checkpoint : MonoBehaviour
{
void OnTriggerEnter(Collider other)
{
if (other.TryGetComponent(out PlayerRespawn respawn))
respawn.SetCheckpoint(transform.position + Vector3.up);
}
}Set up the Layer Collision Matrix so Hazard only interacts with Player, and Pickup only with Player.
Step 7: HUD, audio and best time
A UI Toolkit HUD (UI/HUD.uxml with labels crystals, lives, timer and a hidden banner) driven by the session:
using UnityEngine;
using UnityEngine.UIElements;
[RequireComponent(typeof(UIDocument))]
public class HudView : MonoBehaviour
{
[SerializeField] GameSession session;
Label crystals, lives, timer, banner;
int shownSeconds = -1;
void OnEnable()
{
var root = GetComponent<UIDocument>().rootVisualElement;
crystals = root.Q<Label>("crystals");
lives = root.Q<Label>("lives");
timer = root.Q<Label>("timer");
banner = root.Q<Label>("banner");
session.Changed += Refresh;
}
void OnDisable() => session.Changed -= Refresh;
void Refresh()
{
crystals.text = quot;{session.Crystals}/{session.Level.CrystalsRequired}";
lives.text = quot;Lives {session.Lives}";
int seconds = Mathf.CeilToInt(session.TimeLeft);
if (seconds != shownSeconds) { shownSeconds = seconds; timer.text = quot;{seconds / 60}:{seconds % 60:00}"; }
banner.style.display = session.Current == GameSession.State.Playing ? DisplayStyle.None : DisplayStyle.Flex;
banner.text = session.Current == GameSession.State.Won ? "ESCAPED!" : "CAUGHT";
}
}(The crystal and lives strings still allocate on each Changed event. They change rarely, so that's fine; the timer, which changes every frame, only updates once per second.)
Audio: an AudioSource on the player plays a pickup sound by listening to CrystalCollected, routed to an SFX group of an AudioMixer; music goes to a Music group with an exposed volume.
Best time, saved as JSON when the level is won:
using System.IO;
using UnityEngine;
[System.Serializable]
public class BestTimes
{
public int version = 1;
public string levelId;
public float bestSeconds;
}
public class BestTimeSaver : MonoBehaviour
{
[SerializeField] GameSession session;
[SerializeField] EventChannel levelWon;
string PathFor(string id) => Path.Combine(Application.persistentDataPath, quot;best_{id}.json");
void OnEnable() => levelWon.Raised += Save;
void OnDisable() => levelWon.Raised -= Save;
void Save()
{
string id = session.Level.LevelId;
float used = session.Level.TimeLimit - session.TimeLeft;
string path = PathFor(id);
var best = File.Exists(path) ? JsonUtility.FromJson<BestTimes>(File.ReadAllText(path)) : null;
if (best != null && best.bestSeconds <= used) return;
best = new BestTimes { levelId = id, bestSeconds = used };
File.WriteAllText(path + ".tmp", JsonUtility.ToJson(best, true));
if (File.Exists(path)) File.Delete(path);
File.Move(path + ".tmp", path);
}
}Disable player input when the session ends (listen to LevelWon/LevelLost and set PlayerMover.InputEnabled = false), and add a restart button that reloads the scene.
Step 8: The rules as a runnable model
The game's rules don't need Unity at all. Here they are as plain C#, driven by a scripted run (each event happens at a fixed time), the way you'd unit-test them with the Test Framework. Two runs: one escape, and one where the player dawdles and the timer runs out.
using System;
using System.Collections.Generic;
using System.Text.Json;
var level = new LevelDefinition("level1", CrystalsRequired: 4, TimeLimit: 60, Lives: 3);
string? bestJson = null;
var escape = new (double T, string Event)[]
{
(5, "crystal"), (9, "crystal"), (14, "hit"), (20, "crystal"), (26, "exit"),
(31, "crystal"), (33, "hit"), (38, "exit"),
};
var slow = new (double T, string Event)[] { (10, "crystal"), (30, "crystal"), (45, "hit"), (58, "crystal") };
bestJson = Run("Run 1 (escape)", level, escape, bestJson);
bestJson = Run("Run 2 (too slow)", level, slow, bestJson);
Console.WriteLine(quot;saved best: {bestJson}");
static string? Run(string title, LevelDefinition level, (double T, string Event)[] script, string? bestJson)
{
Console.WriteLine(quot;== {title}");
var s = new Session(level);
double t = 0, dt = 0.5; // the game loop, 2 updates per second for the model
int next = 0;
while (s.State == SessionState.Playing && t <= level.TimeLimit + dt)
{
while (next < script.Length && script[next].T <= t)
{
var e = script[next++].Event;
string result = e switch
{
"crystal" => s.CollectCrystal(),
"hit" => s.Hit(),
"exit" => s.ReachExit(t),
_ => "?"
};
Console.WriteLine(quot; t={t,4:F1} {e,-7} -> {result}");
}
s.Tick(dt);
t += dt;
}
Console.WriteLine(quot; final: {s.State}, crystals {s.Crystals}/{level.CrystalsRequired}, lives {s.Lives}, time left {s.TimeLeft:F1}");
if (s.State != SessionState.Won) return bestJson;
var best = bestJson == null ? null : JsonSerializer.Deserialize<BestTime>(bestJson);
if (best != null && best.Seconds <= s.ElapsedAtWin) return bestJson;
return JsonSerializer.Serialize(new BestTime(level.Id, s.ElapsedAtWin));
}
record LevelDefinition(string Id, int CrystalsRequired, double TimeLimit, int Lives);
record BestTime(string LevelId, double Seconds);
enum SessionState { Playing, Won, Lost }
class Session
{
readonly LevelDefinition level;
public SessionState State { get; private set; } = SessionState.Playing;
public int Crystals { get; private set; }
public int Lives { get; private set; }
public double TimeLeft { get; private set; }
public bool GateOpen => Crystals >= level.CrystalsRequired;
public double ElapsedAtWin { get; private set; }
public Session(LevelDefinition l) { level = l; Lives = l.Lives; TimeLeft = l.TimeLimit; }
public void Tick(double dt)
{
if (State != SessionState.Playing) return;
TimeLeft = Math.Max(0, TimeLeft - dt);
if (TimeLeft == 0) { State = SessionState.Lost; Console.WriteLine(" time's up -> Lost"); }
}
public string CollectCrystal()
{
if (State != SessionState.Playing) return "ignored";
Crystals++;
return Crystals == level.CrystalsRequired ? quot;{Crystals}/{level.CrystalsRequired}, gate opens" : quot;{Crystals}/{level.CrystalsRequired}";
}
public string Hit()
{
if (State != SessionState.Playing) return "ignored";
Lives--;
if (Lives <= 0) { State = SessionState.Lost; return "no lives left -> Lost"; }
return quot;respawn at checkpoint, lives {Lives}";
}
public string ReachExit(double t)
{
if (State != SessionState.Playing) return "ignored";
if (!GateOpen) return quot;gate closed ({level.CrystalsRequired - Crystals} crystal(s) missing)";
State = SessionState.Won;
ElapsedAtWin = t;
return quot;escaped in {t:F1} s -> Won";
}
}== Run 1 (escape)
t= 5.0 crystal -> 1/4
t= 9.0 crystal -> 2/4
t=14.0 hit -> respawn at checkpoint, lives 2
t=20.0 crystal -> 3/4
t=26.0 exit -> gate closed (1 crystal(s) missing)
t=31.0 crystal -> 4/4, gate opens
t=33.0 hit -> respawn at checkpoint, lives 1
t=38.0 exit -> escaped in 38.0 s -> Won
final: Won, crystals 4/4, lives 1, time left 22.0
== Run 2 (too slow)
t=10.0 crystal -> 1/4
t=30.0 crystal -> 2/4
t=45.0 hit -> respawn at checkpoint, lives 2
t=58.0 crystal -> 3/4
time's up -> Lost
final: Lost, crystals 3/4, lives 2, time left 0.0
saved best: {"LevelId":"level1","Seconds":38}
Every rule from the Unity scripts is here: the gate opens exactly when the last crystal is collected, the exit ignores the player until then, hits cost lives, the timer ends the run, and only a better winning time replaces the saved best. If the rules change (bonus time per crystal, say), change and test them here first, then mirror the change in GameSession. Better still, have GameSession delegate to a plain class like Session and test that class directly.
Build it
- Add
Level1(and a menu scene if you made one) to the Scene List in File > Build Profiles. - Make a Development Build for your desktop platform, play it from start to finish, and check the Profiler for GC allocations during play.
- Make a release build with IL2CPP. Give it to someone who has never seen it and watch them play without helping. Write down where they get lost.
Ideas to extend it
- More levels: a
LevelDefinitionper level, loaded with Addressables, and a level select menu. - Juice: crystal pickup tween with DOTween or PrimeTween, camera impulse on hits, particles on the gate.
- A dash with cooldown, moving platforms, a drone that predicts where the player will be.
- Rebinding UI and gamepad rumble when hit.
- A ghost of your best run, recorded as positions per fixed step and replayed.
Test yourself
Why does PlayerMover.Teleport disable the CharacterController before setting the position?
- To save memory
- An enabled CharacterController can override direct transform changes
- To reset gravity
- Unity requires it for every transform change
How do the crystals tell the session they were collected without referencing it?
FindFirstObjectByType<GameSession>()in Update- By raising the shared
CrystalCollectedevent channel asset - Through a static singleton
- With SendMessage
Why test the rules with a plain C# Session class?
- Unity can't run the rules
- Plain classes can be tested quickly without scenes, and the MonoBehaviour can delegate to them
- It makes builds smaller
- Event channels require it