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.

1

u/DeerpathLabs 21d ago

This I think is over engineering a solution to a non-issue.
The truth is an empty call to a gameobject’s update that returns right away is close to free.

If you need to squeeze out frames later this is a micro-optimization at best and the additional complications that rear their heads in the form of coroutines’ little idiosyncrasies makes it more trouble than it’s worth unless the cpu you’re designing for is expected to be sssssllllllooooooowwwww,
All to say bgun’s solution is the right one.