Menu
CoddyTech

Recap: Modular Turret

Part of the Game Architecture in Unity section of Coddy's Unity journey. Lesson 5 of 50.

challenge icon

Challenge

Easy

Build the test range's two turrets from parts. TurretControl.cs already turns each turret with the left and right arrows, and Shell.cs flies a shell forward. The scene gives Turret1 a Cannon and an Ammo with 4 shells, and Turret2 a TwinCannon and an Ammo with 3 shells. Write the parts:

  • Ammo: a public int shells and a public method bool Take(). With a shell left, it uses one and returns true. With none, it logs the object's name and is empty, as Turret2 is empty, and returns false.
  • Weapon: an abstract component that always comes with an Ammo, with a public shellPrefab (a GameObject), a public float cooldown (the Inspector sets 1) and a public method Pull(). A pull during the cooldown does nothing and uses no shell. Otherwise, if Take() gives a shell, the cooldown starts and Fire() runs, an abstract method each weapon writes.
  • Cannon fires one shell from 1 unit in front of the turret. TwinCannon fires two for one shell of ammo, from 0.4 to the left and 0.4 to the right of that spot. A shell starts at transform.position + transform.rotation * offset, turned like the turret (transform.rotation), where offset is the spot seen from the turret, such as new Vector3(0f, 0f, 1f).
  • In TurretControl, Space pulls the trigger of whatever Weapon the turret has.

Press Play, turn and fire until both turrets are empty, then Check.

Try it yourself

using UnityEngine;

// What every turret weapon shares.
public class Weapon : MonoBehaviour
{
}

All lessons in Game Architecture in Unity