Menu
CoddyTech

Recap: Door States

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

challenge icon

Challenge

Medium

A castle door with a lock. The arrows walk the Player, and the gold Key calls door.Unlock() when the player picks it up (both ready). IState and the chapter's StateMachine are in the project. Door.cs has the Inspector's values (closedY 1.5, openY 4, speed 2, stayOpen 2, reach 2.5), a machine field and PlayerNear(). Give the door five states, as classes in DoorStates.cs named LockedState, ClosedState, OpeningState, OpenState and ClosingState:

  • The door starts Locked. Space near it (PlayerNear()) only logs Locked. Unlock() turns a locked door Closed and does nothing in any other state.
  • Closed: Space near the door starts opening it.
  • Opening: the door rises at speed until its y is openY, then it is Open.
  • Open: after stayOpen seconds it starts closing.
  • Closing: the door comes down at speed until its y is closedY, then it is Closed. Space near it on the way down opens it again from where it is.

Press Play, try the locked door, fetch the key, open the door and walk through, then Check.

Try it yourself

using UnityEngine;

// LockedState, ClosedState, OpeningState, OpenState and ClosingState

All lessons in Game Architecture in Unity