Instantiating new instances of states with each switch state

I’m about 75% through the course (and loving it) but had a more general question and wasn’t sure where to put it. I’m a newer developer (about 5 months) so this course is my first exposure to hierarchical state machines. I’ve been watching other videos on youtube about state machines and I noticed other people tend to declare instances of the states in the state machine and store them as a variable. In this course we have been instantiating new instances of the state with each switch state. So my question is…

Is there any advantage or disadvantage to creating a new instance of the state with each switch state? Or is this just two different ways to accomplish the same outcome? Thanks

There are pros and cons of caching states.

As a pro, we can reduce memory usage and garbage collection. Constantly switching between two states can create a small bit of overhead. While no individual state is very large, they can certainly add up over time.

As a con, we need to reset cached states when they are assigned to the state machine.

We didn’t really explore caching states within the course. There are a few things we can change to make the transition easier: One that is fairly easy to implement is Blackboards - Adding a blackboard class allows us to carry over important data from one state to the next. It also eliminates the need for varied constructors. Simply ensuring that the state is pointing at the correct StateMachine is all we need, then the state can get needed data from the Blackboard like the next attack or the carried over momentum in a jump.

Caching states does present other issues, like adding in the complexity of a system that can cache the states to begin with. Solutions can range from a Dictionary<string, State> to store states by a lookup on the individual state machine, or to a full blown Cache for each state type.

It is something I’m exploring in my personal project (based on both the RPG series and this course), but I haven’t settled on whether it’s a net positive to cache or not to cache.

1 Like

Thanks for the detailed answer! I always find your answers very helpful.

Are you ever gonna make your own course?

It’s possible that I may do courses in the future.
The tricky part is that I have a face made for radio, and a voice made for texting…
I’m very comfortable writing code, and writing tutorials on how to create that code. I’m just not terribly comfortable recording videos (which is Ironic, as I have two albums of music on BandCamp).

1 Like

:rofl: Well either way I look forward to any tutorials or content you make.

Privacy & Terms