Recap: Modular Turret
Part of the Game Architecture in Unity section of Coddy's Unity journey. Lesson 5 of 64.
Challenge
EasyBuild Turret1's weapon. TurretControl and Cannon are ready.
- In
Ammo, writepublic bool Take(): use a shell and returntrue, or logname + " is empty"and returnfalse. - Make
Weaponabstract with[RequireComponent(typeof(Ammo))], andFire()protected abstractwith no body. Pull()does nothing duringcooldown; else, ifTake(), restart the cooldown and callFire().
Press Play and fire until it is empty. Then Check.
Try it yourself
using UnityEngine;
// What every turret weapon shares.
public class Weapon : MonoBehaviour
{
public GameObject shellPrefab;
public float cooldown = 1f;
public void Pull()
{
// wait out the cooldown, take a shell from the Ammo, then fire
}
// Each weapon fires its own way.
protected virtual void Fire()
{
}
// A shell from this spot, seen from the turret, flying the way the turret faces.
protected void Launch(Vector3 offset)
{
Instantiate(shellPrefab, transform.position + transform.rotation * offset, transform.rotation);
}
}
All lessons in Game Architecture in Unity
1Components, Not Hierarchies
Small ComponentsA Base Enemy ScriptAbstract ComponentsComponents Working TogetherRecap: Modular TurretRecap: Twin Cannon4Serialized Data
Serializable ClassesLists in the InspectorEnums in the InspectorRecap: Loot TableRecap: Roll the Loot2Interfaces in Unity
IDamageableInterfaces and TryGetComponentGetComponentsRecap: Interact KeyRecap: Nearest in ReachPractice on your own: Unity playground