

In Minecraft you have nasty creatures called Skeletons and Creepers. To illustrate the state pattern we will here make a Mincecraft clone. If (carMode = CarFSM.Park & IsPressingGasPedal())Įlse if (carMode = CarFSM.Forward & IsPressingBrakePedal()) And then you change the state with something like It's common to use enums when coding a state machine in C#, and it looks like this with our car example: The object can only be in one state at a time: you shouldn't accelerate and press the brake pedal at the same time! So the first thing you have to ask yourself is: What are all the states or possible situations the object is going to find itself in? This idea to divide the behavior into a fixed set of states that the object can be in is called a Finite State Machine, or FSM. And what if we are reversing and pressing the forward key, should we brake or accelerate? And what if we have more states than just four? Then you will need the state pattern to avoid nested if-else-statements with several booleans. If we are moving forward and braking, then we don't want to reverse even though the reverse button and the brake button is often the same key. To write this behavior of a car in code is not that simple as it first might seem. If you have a car, it can either drive forward, brake, reverse, or you could have parked it. The basic idea behind the pattern is that what you are trying to control has different states. This pattern is used in computer programming to encapsulate varying behavior for the same object based on its internal state.

#UNITY SIMPLE STATES SOFTWARE#
The state pattern, which closely resembles Strategy Pattern, is a behavioral software design pattern, also known as the objects for states pattern. We begin with Wikipedia's defintion of the state pattern: This tutorial is outdated, you can find the latest version here: GitHub What's the state pattern?
