I am using finite state machines to control entities in my game and I have a state machine class that handles the switching of states. I have an abstract class of EntityState that the player states, enemy states, etc. would inherit from so that I don’t have to retype of bunch of shared logic. I have the StateMachine class storing the current state as an EntityState since the state machine will be dealing with many type of states like PlayerState and all of the EnemyStates.
public class StateMachine
{
public EntityState CurrentState { get; private set; }
public void Initialize(EntityState startingState)
{
CurrentState = startingState;
CurrentState.Enter();
}
public void ChangeState(EntityState newState)
{
CurrentState.Exit();
CurrentState = newState;
CurrentState.Enter();
}
}
If I ever need to call a function on the current state (regardless of what the current state is) from another script I need to reference the current state from the state machine
StateMahcine.CurrentState.SomeFunction()
My issue is that if I ever need to call a function from a derived class (for example PlayerState which is an abstract base class for all my player states) that doesnt exist on EntityState it will fail because the state machine is storing the current state as EntityState and not PlayerState. I could get around this by making many StateMachine child classes that each store the current state as whatever state I need. But I dont want to do this as every time I need to add a new type of enemy or something that uses a FSM I need to add another class.
So my question is that is there a way to change the type of currentstate or store it as a certain type? I would like to tell the StateMachine what type base class to store current state as when it starts. I tried doing this with generics in the constructor but from what I’ve read you cant use generics types in a constructor.