Menu
CoddyTech

Tower Defense Lite

Part of the Game Architecture in Unity section of Coddy's Unity journey. Lesson 61 of 64.

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, and so are the tower's Nearest and Show.

challenge icon

Challenge

Hard

Finish the tower; Nearest(range) and Show() are ready.

  1. TowerLevel: serializable, public range, fireEvery, damage, cost. TowerData holds public List<TowerLevel> levels.
  2. Every fireEvery seconds, if Nearest(range) finds a creep, place a bolt from an ObjectPool<Bolt> at the tower: bolt.Launch(creep, damage, pool.Release).
  3. Show() after Creep.Killed pays bounty and after Space buys the next level for its cost, logging Tower level 2.

Press Play 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;

    // Ready: the creep nearest the tower within range, or null.
    Creep Nearest(float range)
    {
        Creep nearest = null;
        float best = Mathf.Infinity;
        foreach (Collider hit in Physics.OverlapSphere(transform.position, range))
        {
            if (hit.TryGetComponent(out Creep creep))
            {
                float distance = Vector3.Distance(transform.position, creep.transform.position);
                if (distance < best)
                {
                    best = distance;
                    nearest = creep;
                }
            }
        }
        return nearest;
    }

    // Ready: shows the level and the gold, as Level 1, 0 gold.
    void Show()
    {
        infoText.text = "Level " + (level + 1) + ", " + gold + " gold";
    }
}

All lessons in Game Architecture in Unity

Practice on your own: Unity playground