The Alert State
Part of the Game Architecture in Unity section of Coddy's Unity journey. Lesson 36 of 64.
Challenge
MediumAlert the turret when the player comes close.
- In
TurretStates.cs, writeAlertState, given the head and the player. Enter: headColor.red, logIntruder!. Tick: face the player around y. Exit: logAll clear. - In
Turret, writeSetState(IState next): the old state's Exit, then the new one's Enter. - Update alerts within
range, scans otherwise, then ticks the current state.
Press Play and walk close. Then Check.
Try it yourself
using UnityEngine;
public class ScanState : IState
{
private Transform head;
private float angle;
private float direction = 1f;
public ScanState(Transform head)
{
this.head = head;
}
public void Enter()
{
angle = 0f;
direction = 1f;
head.GetComponent<Renderer>().material.color = Color.green;
}
public void Tick()
{
angle += 90f * direction * Time.deltaTime;
if (angle > 45f)
{
angle = 45f;
direction = -1f;
}
if (angle < -45f)
{
angle = -45f;
direction = 1f;
}
head.localRotation = Quaternion.Euler(0f, angle, 0f);
}
public void Exit()
{
}
}
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 Loot7State Machines
States as ClassesThe Alert StateA State MachineTransitionsEnemy BrainsThe Knight AttacksRecap: Door States2Interfaces in Unity
IDamageableInterfaces and TryGetComponentGetComponentsRecap: Interact KeyRecap: Nearest in ReachPractice on your own: Unity playground