We're going to create a C# interface
and implement it in BeginState
, but incorrectly to see some errors. Then we'll implement the interface correctly. Perform the following steps:
Code
folder and select Add | New Folder.Interfaces
.Interfaces
folder and select Add | New File.In the MonoDevelop Solution window, your file structure will now look like the following screenshot:
Now edit IStateBase
file as follows:
namespace
will move up to line 1.nam
espace Assets.Code.Interfaces.
IStateBase
code block, add line 5: void StateUpdate();
.void ShowIt();
.The IStateBase
file will now look like the following screenshot:
Now we're going to have the BeginState
class partly implementing the IStateBase
interface so that we can see how using an interface
guarantees our State classes meet the minimum requirements for the State Machine.
Now edit the BeginState
class as shown in the following steps:
using Assets.Code.Interfaces;
.public class BeginState : IStateBase
.We have now partly implemented the IStateBase
interface. BeginState
should now look like the following screenshot:
We were just told by Unity that we messed up. There are two errors informing us that BeginState
did not properly implement the two methods required by the IStateBase
interface: StateUpdate()
and ShowIt()
.
Now let's almost correct the code in the BeginState
class:
StateUpdate()
method as StateUpdatee()
:e
from StateUpdatee()
)The Console
output should be exactly as it was before we created and implemented the IStateBase
interface. Even though more methods were added to BeginState
, there's nothing in the code blocks to execute, nor did we change StateManager
to call the methods. Our focus was to show how to implement an interface, and how it guarantees that the interface methods for a class are included correctly.
In a later chapter, we will be adding a third method to IStateBase
named StateFixedUpdate()
. You may add it now if you wish. This will require you to implement the StateFixedUpdate()
method in all States we create.
Q1. What is the main reason to incorporate a State Machine into a game?
Q2. Since State classes aren't attached to GameObjects, how does the code in a State get executed?
Q3. How many States are allowed in a State Machine?
Q4. What should you use to guarantee that all States have the required code for the State Machine to operate properly?
18.188.37.136