The heart of the State Machine is the StateManager
script. This is a Unity class, so it inherits from the MonoBehaviour
class. The script is attached to a GameObject to become a Component. The following are the three core features that the StateManager
script handles:
The StateManager
script is like any other Unity script. It is attached to a GameObject and becomes a Component object. The StateManager
script uses the Update()
method to pass the game control to the active State as shown in the following diagram:
The game control code that's usually in an Update()
method is instead delegated to the StateUpdate()
method on the activeState
object. So every time Unity calls the Update()
method on the StateManager
Component, the StateUpdate()
method is called on the currently active State object.
No matter how many States you may use to control your game, always remember the following points:
StateUpdate()
method, guaranteedStateUpdate()
method on every State, depending on what you want each State to accomplishEach State determines why and when to switch to another State. You could have an almost unlimited number of reasons to switch to another State, such as losing the game, winning the game, touching some special GameObject, solving a puzzle, or the user pressing a button. No matter what the reason is, it's the code in the active State that will trigger the switch to another State.
The SwitchState()
method on the StateManager
script is called to accomplish this.
When the active State has been determined, it is time to switch to another State; the SwitchState()
method on the StateManager
is called. SwitchState()
takes an argument of the new State, which will become active next.
This newly created State is then assigned to the activeState
variable. Why?
In order for a State to control a game, StateManager
needs to know about it. A reference of the active State object is stored in the activeState
variable.
So when Unity calls Update()
on the StateManager
script, control is passed to the newly created State that's stored in activeState
by calling its StateUpdate()
method. The State Machine cycle of changing to a new State is complete.
Review the following steps:
StateManager
script using the SwitchState()
method.activeSt
ate
variable.Update()
is called on StateManager
, the Update()
method delegates control to the StateUpdate()
method on the new State.3.145.61.170