- Home /
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?
Awesome question, I'm definitely going to have some input here but not tonight. I took an approach through the animator where every animation was treated as a state by using scripts inheriting from State$$anonymous$$achineBehaviour. The animator component is automatically from each animation to the next as a parameter and is setup with Enter, Update, and Exit functions.
Answer by Glurth · Jun 09, 2019 at 09:54 PM
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
Great article! I really enjoyed the explanations step by step structure of how to improve finite state machines. Thanks for sharing it!
Answer by Kennai · Jun 10, 2019 at 11:54 AM
Hi, @Frepperino ! I use Animation and AnimationController for state machine. Here is a good explanation how to do it: https://www.youtube.com/watch?v=dYi-i83sq5g
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.
Your answer
![](https://koobas.hobune.stream/wayback/20220612202911im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
Multiple Cars not working 1 Answer
Distribute terrain in zones 3 Answers
How do i use StateMachine logic with my code ? 1 Answer
State Machine Question 1 Answer
Interface state structure with different type of enemies 0 Answers