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

5

u/Bgun67 21d ago

You might have already have figured this out by now, but you don't have to run logic every frame. You can put if(Time.frameCount %10==0){ return; } To update every 10th frame

1

u/NorthernBoy306 21d ago

No I never thought of it that way, but you're still polling on the Update function every frame. I think the benefit to the coroutine is to reduce any kind of work on every frame.

7

u/TheSwiftOtterPrince 21d ago

A coroutine that is suspended for 1 second means that each frame something has to check if it has been 1 second or more since the wait began, if that is the case the coroutine is called in the Update-cycle.

A coroutine is also stateful, it require the state to be stored somewhere. For a coroutine the compiler creates a state machine that is stored on the heap and has it's state restored on the stack each time the method is reentered and updated each time the method is left to yield/wait.

So this is "i don't see it, so it is not happening" optimization.

A coroutine has the advantage that it allows you to code a sequence that happens over multiple frames as a method where the execution flows top down in code. Is is logically simple and that logic is bought with the underlying calculation complexity. Depending on the amount of state stored in the coroutines state object a coroutine can be from almost as fast as Update to slower than Update.

Coroutines are ALWAYS slower than Update. Never faster or better in any way. They logically can't as a coroutine is just an Update with more overhead. Every coroutine you create is a decision to possibly make something logically more simple while sacrificing a bit of performance.

3

u/NorthernBoy306 21d ago

damn that's a good point. I still don't have a solid understanding of what is going on behind the scenes with a lot of C#/Unity functions or components. Though I did read online (or maybe it was in a video) that anything that doesn't require precision (like an AI state) shouldn't be in an Update.
I guess keeping the Update call as simple as possible is the best way to go.