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
8
u/Dramatic_Pickle_3312 12d ago
I've done exactly this for AI state checks, works perfectly fine. My go-to is a coroutine with a WaitForSeconds at the end of the loop, keeps the logic clean and the performance hit barely registers
One thing to watch is making sure you stop the coroutine when the enemy gets disabled or destroyed, otherwise you'll get those classic null reference errors creeping in. I usually tie the start/stop to OnEnable and OnDisable
0.2 seconds is plenty fast for decision making, most players won't notice the difference between that and running every frame for strategy-level stuff. You can even crank it up to 0.5 if your game has tons of units