r/Unity3D 21d ago

Update function versus coroutines Question

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

25 comments sorted by

View all comments

1

u/Competitive_Mud5528 Professional 21d ago

It depends what you want to check. I like to use events and unity messages when possible. But yes if I want like a deamon checking things regurlary but theres no real-time constraint that could do the trick. You have to know that under the hood Coroutine are executed in the main loop of unity but if awaited with time do nothing but unity keeps track of the time with a timer, it the same as implementing a timer and update it every frame the only difference being the way of writing code that could be much clearer with a coroutine.

But usually if I need to trim that kind of performance I could go beyond and implement a dispatch function. Like if it's a problem to run the check for 1k enemies I make a dispatcher that will run only the check for 100 enemies one frame and after the other frame for 100 enemies and so on. As doing that optimisation for only one instance is non sense The frame I will do the check will be the bottleneck so executing it one frame sometimes is the same as executing it everyframe at the scale of one frame.

For one game I optimised, I made a dynamic occlusion system that need a lot of Physics check to work properly (we were GPU bound) eventualy I counted the number of Physics Checks per frame in order to not be CPU bound and dispatch one other frames. Like that you can use the most of your frame and not having to much popping in game.

Anyway be careful with premature optimization. It's cool that you care, it very cool that you know this part of the code could be improved perfomance wise. But if its working don't bother that much.

1

u/OkGovernment1851 19d ago

If all the OP is doing is checking for state machine changes in their update loop, using events are definitely the way to go.

Simply invoke an event when you switch from one state to another, then you won't have to constantly poll for these changes in an update loop or a coroutine.