The beauty of a State Machine lies in its simplicity, and you are already familiar with the concept. You probably spent at least the first 14 years, maybe more, of your life living in a State Machine environment; you just didn't know that it was a State Machine at the time.
As a child, your parents were always making you take a bath, go to school, do your homework, go to sleep, and whatever else you always had to do. When you were in school, you were in the school State. Were you allowed to do anything else? While sleeping, you were in your sleep State. Were you allowed to do anything else? How about the do your homework State?
The idea of being in a certain State is that you can only do what's allowed in that particular State, but you do it very well. When you put a computer program in a particular State, it will stay in that State doing only what it's supposed to do until it's told to change to another State. This is exactly what you want to do in Unity, put your game into a particular State to perform the specific behaviors you desire.
The following are the benefits of using a State Machine:
The primary benefit of using a State Machine is for code organization. Typically, a game may start off being simple and following the code flow is easy. Unfortunately, games don't seem to stay simple. Features are added, code has to be changed with if
statement after if
statement added to control the game logic. It turns into a nightmare just trying to to keep track of where a specific pieces of code may be located. You'd probably add more Components to GameObjects to try to make the logic sensible. Even worse would be the use of global variables to pass data around to Components. Then you have to keep track of which Components access which global variables and hope the data stored is what you think it is at the time you access it. Trying to follow the logic ends up being like a bowl of spaghetti.
Doesn't it make sense to use the capabilities of C# to create specific State objects to keep game logic well organized, instead of attaching Components to GameObjects filled with the spaghetti code?
The following diagram is the basic concept of a State Machine for controlling a Unity project:
Update()
method every frameStateManager
script is the heart of the State Machine, a Component that has the Update()
methodUpdate()
delegates (transfers) control to the State that is active3.145.75.217