Tower Defense Lite
Part of the Game Architecture in Unity section of Coddy's Unity journey. Lesson 48 of 50.
Creeps march along the road toward your base, and a single tower guards it. The tower shoots bolts at the creep nearest to it while one is in range, and every creep it brings down pays gold. Space spends the gold on the tower's next level: each level reaches further, shoots faster or hits harder. A creep that reaches the base gets through. The levels are game data that a designer tunes in an asset, without touching the code, and the tower fires a lot of bolts, so it reuses them from a pool instead of making and destroying one for every shot.
Write two scripts: TowerData, the asset type, and Tower. Creep, Bolt and CreepSpawner are ready.
Challenge
HardThe Inspector gives Tower data (the Arrow asset), boltPrefab and infoText. Read Space through the Input System's Keyboard.current.
- In
TowerData.cs: a classTowerLevelthat the Inspector can show, withpublic float range,public float fireEvery,public int damageandpublic int cost(the price of reaching that level), andTowerData, a ScriptableObject with a Create menu entry and apublic List<TowerLevel> levels. The Arrow asset holds three levels: range 4, every 1 s, damage 1, cost 0; range 5, every 0.6 s, damage 1, cost 6; range 6, every 0.4 s, damage 2, cost 12. - The tower starts at the first level with 0 gold, and
infoTextshows both, asLevel 1, 0 gold, whenever they change. - When the level's
fireEveryseconds have passed since the last shot and a creep is in range (a creep's collider withinrangeof the tower, asPhysics.OverlapSpherefinds it), the tower shoots the creep nearest to it. It takes a bolt from anObjectPool<Bolt>, puts it at the tower, and callsbolt.Launch(creep, damage, pool.Release): the bolt calls that last argument when it is done, which gives it back to the pool. A bolt is deactivated while it waits in the pool and activated when it is taken. - Every creep that dies pays its
bountyin gold: listen to the static eventCreep.Killed. - Space buys the next level, when there is one and the gold covers its
cost: the cost comes off the gold, and the tower moves up and logs it, asTower level 2. Otherwise Space does nothing.
Press Play, hold the road and upgrade, then Check.
Try it yourself
using UnityEngine;
using UnityEngine.InputSystem;
using UnityEngine.Pool;
using TMPro;
public class Tower : MonoBehaviour
{
[SerializeField] private TowerData data;
[SerializeField] private Bolt boltPrefab;
[SerializeField] private TMP_Text infoText;
private int level;
private int gold;
}
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Game Architecture in Unity
1Components, Not Hierarchies
Small ComponentsA Base Enemy ScriptAbstract ComponentsComponents Working TogetherRecap: Modular Turret10Project: Arena Survivor
The HeroEnemy Types