Is there a reason why a statemachine pattern is not used for actions instead of a flag?
The method Hugo used is a valid state machine. I personally don’t like switch statements so I went with a simple Action
delegate method instead. I think building a full state machine to achieve what we did may have been overkill. Perhaps Hugo just opted for the simpler solution. But there’s no reason why you couldn’t replace it with a state machine if that’s what you’d prefer
State Machines come in many shapes and sizes. Hugo actually does use simple state machines (an switch on enum is a valid State Machine) in several of the classes, albeit a very simple State Machine).
While you can replace this with a more formal state machine style, I caution against adding too much complication if it’s not truly needed.
Thanks,
I am more of an enum/switch-person when it comes to few states with some limited scaling - just to be able to see the states clearly and get a good view on enter/exit. But for learning purposes i will look into the Action delegate alternative - as suggested.
The Action
delegate is simple, really. You just have an Action
that executes every frame, and you change it out with whichever code (state) should run. Here’s a simple example
private Action _currentState;
private void Awake()
{
_currentState = IdleState; // set the initial state
}
private void Update()
{
_currentState?.Invoke(); // execute the state
}
private void IdleState()
{
// Do nothing
}
private void AimState()
{
// Do aim stuff
// switch state if needed
_stateTimer -= Time.delatTime;
if (_stateTimer <= 0f)
{
_stateTimer = 0.1f; // shooting state time
_currentState = ShootState;
}
}
private void ShootState()
{
// Do shoot stuff
// switch state if needed
_stateTimer -= Time.delatTime;
if (_stateTimer <= 0f)
{
ActionComplete();
_currentState = IdleState;
}
}
public override void TakeAction(GridPosition gridPosition, Action onActionComplete)
{
_targetUnit = LevelGrid.Instance.GetUnitAtGridPosition(gridPosition);
canShootBullet = true;
ActionStart(onActionComplete);
_stateTimer = 1f;
_currentState = AimState;
}
This was very good and simple! I think this is the end to my enum adventures…!
This topic was automatically closed 24 hours after the last reply. New replies are no longer allowed.