Once we modify BeginState
, we'll essentially use it as a sort of template for creating all the other States, with just a few minor differences.
Using the next screenshot of BeginState
, make the following changes:
private StateManager manager;
.public BeginState(StateManager managerRef).
manager = managerRef;
.Follow these next steps three times to create the other State classes: PlayState
, WonState
, and LostState
.
In the Solution window of MonoDevelop, perform the following steps:
States
folder, and select Add | New File.In each of the three new files, make them almost identical to the code of BeginState
except for the class name, the constructor method name, and the text in the Debug.Log
statement.
Line 6 on each respective class file will be as follows:
public class PlayState : IStateBase
public class WonState : IStateBase
public class LostState : IStateBase
Line 10 on each respective class file will be as follows:
public PlayState (StateManager managerRef)
//Constructor
public WonState (StateManager managerRef)
//Constructor
public LostState (StateManager managerRef)
//Constructor
Line 13 on each respective class file will be as follows:
Debug.Log("Constructing PlayState");
Debug.Log("Constructing WonState");
Debug.Log("Constructing LostState");
Each State is responsible for determining why and when to switch to another State. Since there is no game code at this point, we need to manually switch States to test the State Machine. We will do this by Unity detecting when we press the Space bar key.
Add the following if
statements to the
StateUpdate()
method code block (line 18 in the previous screenshot) for each State:
In the BeginState
class line 18:
if (Input.GetKeyUp (KeyCode.Space)) { manager.SwitchState (new PlayState (manager)); }
In the PlayState
class line 18:
if (Input.GetKeyUp (KeyCode.Space)) { manager.SwitchState (new WonState (manager)); }
In the WonState
class line 18:
if (Input.GetKeyUp (KeyCode.Space)) { manager.SwitchState (new BeginState (manager)); }
In the LostState
class line 18:
if (Input.GetKeyUp (KeyCode.Space)) { manager.SwitchState (new BeginState (manager)); }
We modified
BeginState
so that it would have a reference to StateManager
, which is the controller for State switching. Once BeginState
was properly coded, we created three more similar State classes: PlayState
, WonState
, and LostState
. We now have enough code in the State classes for testing the State Machine. Now let's modify the StateManager
class.
3.128.226.121