Use existing states instead of a "new" one everytime

I’m a bit concerned about creating a new state every time we transition, what if we have some state saved on a state and want to keep it?

#1 How would one use previously created states while transitioning from one to another?

Which brings me to my second question - Why are the states themselves transitioning to a new state? Shouldn’t it be handled by the State Manager? A cartridge is not the one that pulls itself out and put the other one in.

#2 Would something like this be better? Does it break any principle?

public interface ILocomotionState
{
    ILocomotionState GetStateFromJump();
}

class LocomotionStatePattern : MonoBehaviour
{
    ILocomotionState currentState = new StandingState();

    private void Jump()
    {
        currentState = currentState.GetStateFromJump();
    }
}
2 Likes

Generally speaking, you’ll be extending this skeleton state machine with supporting data. In this case, caching a state may introduce more bugs than the extra overhead that the new states create. While the State pattern is actually one of my least favorite patterns, this is the way generally accepted by the authors of Design Patterns. Since the classes aren’t MonoBehaviors, the overhead isn’t nearly as great as creating a component or instantiating a prefab. You could consider the Object Pooling (Factory) pattern later in the course.

I can’t see the alternative you’ve started on as being a better pattern, without a great deal more context.

1 Like

Privacy & Terms