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
HardFinish the tower; Nearest(range) and Show() are ready.
TowerLevel: serializable, publicrange,fireEvery,damage,cost.TowerDataholdspublic List<TowerLevel> levels.- Every
fireEveryseconds, ifNearest(range)finds a creep, place a bolt from anObjectPool<Bolt>at the tower:bolt.Launch(creep, damage, pool.Release). Show()afterCreep.Killedpaysbountyand after Space buys the next level for itscost, loggingTower 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
1Components, Not Hierarchies
Small ComponentsA Base Enemy ScriptAbstract ComponentsComponents Working TogetherRecap: Modular TurretRecap: Twin Cannon4Serialized Data
Serializable ClassesLists in the InspectorEnums in the InspectorRecap: Loot TableRecap: Roll the Loot2Interfaces in Unity
IDamageableInterfaces and TryGetComponentGetComponentsRecap: Interact KeyRecap: Nearest in ReachPractice on your own: Unity playground