Recap: Modular Turret
Part of the Game Architecture in Unity section of Coddy's Unity journey. Lesson 5 of 50.
Challenge
EasyBuild 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
shellsand a public methodbool Take(). With a shell left, it uses one and returnstrue. With none, it logs the object's name andis empty, asTurret2 is empty, and returnsfalse. - Weapon: an abstract component that always comes with an Ammo, with a public
shellPrefab(a GameObject), a public floatcooldown(the Inspector sets 1) and a public methodPull(). A pull during the cooldown does nothing and uses no shell. Otherwise, ifTake()gives a shell, the cooldown starts andFire()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), whereoffsetis the spot seen from the turret, such asnew 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
1Components, Not Hierarchies
Small ComponentsA Base Enemy ScriptAbstract ComponentsComponents Working TogetherRecap: Modular Turret10Project: Arena Survivor
The HeroEnemy Types