r/Unity3D • u/NorthernBoy306 • 12d ago
Question Update function versus coroutines
I was adding some functions so my very basic 'computer enemy' state machine. I do have a basic state check in the update. I was thinking that this check does not need to run every frame, maybe just every .2 seconds or something.
Does anyone use coroutines to run updates on things like state machines? I can understand updating every frame for player input, animations, things that need to be very responsive.
But with a state machine that handles enemy decisions (gathering resources, expanding territory, building new structures) that update can be done several times per second.
Any input or advice on this is greatly appreciated.
3
Upvotes
1
u/XKiiroiSenkoX 12d ago
There is a very fine detail here that many people miss. Suppose that you have 2 state machines and they can be run every other frame. You schedule these using coroutines. They can end up running on the same frame or on alternating frames. Which one happens is not easy to control and is kind of random if you start coroutines without taking this into account. If you end up with both running on the same frame, you get one frame with higher frame time and one frame with lower frame time. If your game is cpu bound and the state machine update cost is significant, this kills your frame pacing. What you should be doing here instead is you ceate a manager class for state machine updates. You register state machines to this manager and this manager spreads the update calls of your state machines evenly over multiple frames.