Interface IStateBase
IStateBase - Interface
IStateBase is a custom interface that we will have all StateX classes implement. This guarantees that all States will implement all Properties and Methods defined in this interface.
C# Interfaces in Unity
Interfaces provide a way to define a set of behaviors that we want to insure are implemented across several classes. C# has single inheritance, which specifies that any C# class can only have 1 parent class. For most of our Unity custom code, MonoBehaviour is that base-class. So, in order to implement related behavior across different classes, we'll use interfaces, since a C# class can implement any number of interfaces.
Interface Specifications, Requirements:
A C# interface can specify method signatures and properties
Any class that implements an Interface MUST provide code to implement every method and property defined in the interface.
All methods defined in an interface are public by default, but the access modifier is only specified in classes that implement the interface.
Methods are specified in an interface as signatures: return_Type, Method_Name, Input_Parameters, they do not have any code to provide implementation logic.
An Interface data-type can be used when defining variables or data-structures - where the actual object instances can be of any class that implements the interface.
StateManager: IStateBase activeState
StateManager, will use an IStateBase reference-type variable to keep track of the current activeState instance. StateManager will execute the methods defined the interface IStateBase for the currently activeState. StateManager delegates responsibility to the current activeState using these methods.
IStateBase activeState;
//the data-type of activeState is IStateBase
IStateBase - Why do we need it?
We'll use the IStateBase activeState variable it to refer to the currently active state within the StateManager class. StateManager's activeState variable is the required: FSM memory of the currently active state. With this reference to the current activeState the StateManager can activate methods (execute functions) on the activeState, even though the states will be changing throughout the course of the game, across different scenes. Although an FSM does not maintain a history of prior stats, we could write code to create a List<IStateBase> to keep track of all of the prior states that the player has visited - we'd want to push some token which represents a state onto an ordered list - then these can be accessed as necessary from other objects.
Here's how we use it:
Code in StateManager.cs to declare reference-type variable: activeState activeState is initialized to refer to an instance of BeginState, a class that implements IStateBase. This code fulfills the FMS requirement to specify the Starting State for an FSM.
Code: IStateBase
Last updated