This is in response to the Creating Our State Machine video.
First thing is pretty easy - the challenge said to create a void SwitchState method. I think that its beneficial to note that this should be a public method. As I am not aware of what the author’s direction was, I had to ensure I watched everything he did afterward to switch the private void to a public void.
Second thing - this is more a philosophical bend on abstract classes. An abstract State class that only houses three abstract methods and does nothing else to me is better suited as an interface. In my project I called it IGameState.
I have worked several places in my career where a code review will get dinged for empty abstract classes like this. Abstract classes are (again opinion-based) best served as places where duplicated code gets consolidated into to adhere to the SINGLE-USE principal (SOLID). In the instance where there is no code, an Interface will also ensure that any classes implementing it will have the public methods defined in the interface.
Of course - both will work just fine but as a best practice I wanted to put the interface forward instead of the abstract State class which then has an abstract other State class which then has a concrete state class added to it. That type of inheritance chain can get unwieldly, especially during maintenance phase of a project.
public abstract class StateMachine : MonoBehaviour
{
private IGameState _currentState;
private void Update()
{
_currentState?.Tick(Time.deltaTime);
}
public void SwitchState(IGameState newState)
{
_currentState?.Exit();
_currentState = newState;
_currentState?.Enter();
}
}