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
MediumIDamageabledeclaresvoid TakeDamage(int amount). MakeEnemyimplement it: the amount comes off its health, and at 0 or less the enemy is destroyed.- In
Projectile, add a serialized floatspeed(the prefab sets 12) andpublic void Launch(Transform target, int damage), which keeps both. InUpdate, fly toward the target atspeed; on arrival, callTakeDamage(damage)on its IDamageable and destroy the projectile. When the target is gone, destroy the projectile. - In
Tower, add a public intdamage, a public floatfireRate(shots per second) and a serializedprojectilePrefab(a Projectile). While the tower has a target, fire at mostfireRatetimes per second: instantiate the projectile a little in front of the head, athead.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
{
}
This lesson includes a short quiz. Start the lesson to answer it and track your progress.