Menu
CoddyTech

Shoot

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

A tower fires a Projectile at its target. The shot flies there with MoveTowards, following the target as it walks, and hurts it on arrival. It does not need to know it hit an Enemy: it asks for IDamageable, the interface for anything that can take damage, so anything that implements it can be shot.

A target can die while a shot is in the air. A destroyed Unity object compares equal to null, so the shot checks target == null first and destroys itself.

For now a tower fires once a second. It keeps the time of its next shot:

if (Time.time >= nextShot)
{
    Fire();
    nextShot = Time.time + 1f;
}
challenge icon

Challenge

Medium

Towers shoot arrows, once a second.

  1. Enemy implements IDamageable: TakeDamage(int amount) takes it off health, destroying the enemy at 0 or less.
  2. Projectile: Launch(Transform target, int damage) keeps both; Update flies to the target at speed, calls TakeDamage(damage) on arrival and destroys itself, also when the target is gone.
  3. Tower: add public int damage = 2; and [SerializeField] private Projectile projectilePrefab;; fire as above from transform.position + Vector3.up.

Press Play: arrows fly and Grunts fall. Then Check.

Try it yourself

using UnityEngine;

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

All lessons in Unity Game: Tower Defense

Practice on your own: Unity playground