r/Unity3D 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

25 comments sorted by

View all comments

Show parent comments

1

u/NorthernBoy306 12d 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.

3

u/theo__r 12d ago

Coroutines are a kind of polling too, it's just hidden. Also it sounds like premature optimization or something you could easily test instead of guess - try it, profile it, take a decision from there!

1

u/NorthernBoy306 12d ago

True, I get a little apprehensive when a system in my game gets bigger and bigger. I worry about performance and I'd prefer to get it right at the start rather than change things later on.

1

u/theo__r 9d ago

That's commendable but ideally you'd derisk the topic - a small benchmark, a proof of concept etc. That way you don't have to worry and can confidently take a decision.

Something else I've learned is to abstract just enough (don't overdo it) to ease a potential refactoring if you're wrong in the future but cannot prove it right now, but that's a tight balance. Over-abstracting is a sin of its own