Menu
CoddyTech

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 icon

Challenge

Hard

The Inspector gives Tower data (the Arrow asset), boltPrefab and infoText. Read Space through the Input System's Keyboard.current.

  • In TowerData.cs: a class TowerLevel that the Inspector can show, with public float range, public float fireEvery, public int damage and public int cost (the price of reaching that level), and TowerData, a ScriptableObject with a Create menu entry and a public 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 infoText shows both, as Level 1, 0 gold, whenever they change.
  • When the level's fireEvery seconds have passed since the last shot and a creep is in range (a creep's collider within range of the tower, as Physics.OverlapSphere finds it), the tower shoots the creep nearest to it. It takes a bolt from an ObjectPool<Bolt>, puts it at the tower, and calls bolt.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 bounty in gold: listen to the static event Creep.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, as Tower 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;
}
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Game Architecture in Unity