Menu
CoddyTech

Fire

Lesson 9 of 18 in Coddy's Unity Game: Tower Defense course.

A tower fires at its target fireRate times per second. Rather than a timer that counts down, the tower keeps the time of its next shot: when Time.time has reached it, the tower fires and moves it on by 1f / fireRate seconds. A sprinkler that sprays twice a second:

if (Time.time >= nextSpray)
{
    Spray();
    nextSpray = Time.time + 1f / spraysPerSecond;
}

Each shot is a Projectile that flies to its target with MoveTowards, following it as it walks, and hurts it on arrival. It does not need to know that it hit an Enemy: it asks the target for IDamageable, the interface for anything that can take damage, as in the Interfaces chapter, so anything that implements it can be shot.

A target can die while a shot is in the air, brought down by another tower's shot. The shot's target then compares equal to null, as every destroyed Unity object does, and the shot has nothing left to fly to, so it destroys itself.

challenge icon

Challenge

Medium
  1. IDamageable declares void TakeDamage(int amount). Make Enemy implement it: the amount comes off its health, and at 0 or less the enemy is destroyed.
  2. In Projectile, add a serialized float speed (the prefab sets 12) and public void Launch(Transform target, int damage), which keeps both. In Update, fly toward the target at speed; on arrival, call TakeDamage(damage) on its IDamageable and destroy the projectile. When the target is gone, destroy the projectile.
  3. In Tower, add a public int damage, a public float fireRate (shots per second) and a serialized projectilePrefab (a Projectile). While the tower has a target, fire at most fireRate times per second: instantiate the projectile a little in front of the head, at head.position + head.forward * 0.6f, and launch it at the target with the tower's damage.

The ArrowTower prefab sets a damage of 2 and a fireRate of 1.5, and its projectile is ArrowShot. Press Play, build towers and stop the first wave, then Check.

Try it yourself

using UnityEngine;

// Comes later: a shot that flies from a tower to its target.
public class Projectile : MonoBehaviour
{
}
quiz iconTest yourself

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

All lessons in Unity Game: Tower Defense