Coroutines or update method with switch statement as state machine

Hi everyone!

I have no specific problem I just mean to ask what’s the more efficient way to make a state machine. Using coroutines where one coroutines end means that start of another, or alternatively, just a switch statement inside the Update method where you call functions based on an enums value?

What’s the pros and cons of the different approaches, and is there perhaps another more efficient way that I do not know of?

I prefer the hierarchical state machine method; a bit more work to get set up, but saves a lot of headaches.

I had typed up 1/2 of a huge answer, but this tutorial is much better that what I came up with.
The hierarchical version is down near the bottom of this article, but suggest you start at the top, even just to skim it.
https://gameprogrammingpatterns.com/state.html

Hi, @Frepperino ! I use Animation and AnimationController for state machine. Here is a good explanation how to do it:

but keep in mind that this “state” machines is runing in multithreads.

Pros:

  • Easy to manage states, easy to change
    different AI behaviours. States are visualized!
  • It makes it work very fast. in my
    game I use about 20-30 state machines
    and it works perfect even on phone!

Cons: if script in states is using same variable, you may need to use
lock to share access one by one between threads.

If you are interested, I can share my state structure, its very easy to enhance and add new states.