Chapter 8. Developing the State Machine

It's time to code the State Machine so we can test its operation. We need to write the code for four initial States, the StateManager, and use the IStateBase interface. We will first have the State Machine work with three States and then show how easy it is to add in the fourth State.

Your Unity project may need more than four States. After you see how easy it is to add a State and how clean, simple, and organized it makes your code, your imagination may run wild on how you could make use of these States.

The whole purpose of Object Oriented Programming (OOP) is to create objects, (little packages of data) and action code (methods). In Unity, these objects are used for controlling actions in your Unity project, and they communicate with each other as well. A State Machine is simply a design choice for these objects that allows you to better organize and maintain your code.

The topics covered for the State Machine are as follows:

  • Creating State classes
  • The StateManager controller
  • The active State and Unity's Scene
  • Changing the Scenes

Well then, let's get stated...

Creating four State classes

As we create each State, you'll notice that each one is identical in structure. Again, this structure, this class interface, is guaranteed to be identical because implementing IStateBase makes it a requirement that certain methods are included in each State.

When we modify the StateManager, you'll see that it guarantees each State will implement the IStateBase interface as a requirement for being a part of the State Machine.

We already have BeginState started from the previous chapter, but it needs some modification to be functional in the State Machine. So let's modify BeginState first, and then create the other three States: PlayState, WonState, and LostState.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.118.139.224