I think I’m starting to abuse coroutines to the degree that I’m loosing control of my Update. HALP.
Maybe wait for seconds?
Yield to your good sense.
Wait for a While but Return with your non-null solution… uhm… semi-colon.
I’ve got rid of all mine because I suck at managing them.
Coroutines, how do I use thee? Let me enumerate the ways.
Since last year I use them all the time, they’re a great way to manage finite time-based operations. I haven’t had too much trouble managing them - I generally hold them in container Coroutine variables and just if (!null) stopcoroutine(x) whenever I want to restart.
That said, I’m not sure if I understand the thread …
I very rarly ever use them. Literally, everything I can do with a CoRoutine I can do with a simple float timer. (Majority of cases). But of course I don’t do much web downloading or anything with WWW or anything. That I do use CoRoutines an such, but I’d much rather multi-thread some background task than using co-routines. I only find them useful if you are downloading things from the web like receiving info from a database or something.
What are you using them for that this becomes an issue?
I mostly find them useful in UI code, for things like “Start a screen transition, wait X seconds, the load this scene”. If I want something that integrates with the Update loop I generally use a fully fledged timer object of some kind. Less “efficient”, but far more control over the time aspect of things, and it’s pretty rare so the efficiency thing isn’t a problem.
Delegates, son, you gotta use the delegates!
I’m still firmly addicted. My latest project even has a static helper class that is built primary with IEnumerators to be consumed by coroutines. Complete with return values via delegates. I may live to regret the decision, but so far its working great.
Coroutines are like tiny little minions that you can deploy to do the work that is beneath the dignity of a MonoBehaviour.
Coroutines have several advantages that make me prefer them over timers in Update for many cases.
- Coroutines are cleaner then Update for simple state machine like behaviour
- Coroutines don’t get called if they are not needed, making it great for things that are only active for short times. Or for things that have long gaps between calls.
- Coroutines are great for things that terminate. On the other hand Update is forever.
Of course I totally understand coroutines becoming unmanageable. Here are some of my rules for managing them.
- All of a coroutines state should be contained within the coroutine.
- A coroutine should be fully self contained, if it needs to take instructions or interact with other code, make it a full class.
- Only one coroutine should ever be acting on a single variable at any point in time.
- Coroutines should be called on the MonoBehaviour/GameObject that they are acting on
This is true. Even the www class you mentioned can be fully controlled without ever resorting to a coroutine.
Its also possible to build complete games from scratch in Assembly.
I use them to control everything in my battle system, every “event” (an animation, a visual effect, hp bar decreasing/increasing, text being displayed, waiting for player input, etc) in this battle system has a duration and they need to happen one by one without going to the next one, in this project I’m working on I didn’t have any problem with them, all the coroutines are being started by only one monobehaviour and all of them is being started with yield return so there is no way to start coroutines and they keep running on the background without I know, if that happens (it never happened) everything will get stuck. haha
I have no idea how I would make my battle system without the coroutines!
edit: Oh, btw, I never start my coroutines in Update, it looks “dangerous”.
I’m interested to know what you mean by this. Do you just mean that once you create a MonoBehaviour it exists until you destroy it (which is indeed a fair chunk of work for something like one timed function), or do you mean something else?
I often have MonoBehaviours that set themselves up for some future use in Start or Awake and then disable themselves (“enabled = false;”). At some point in the future a function call or, more often, an event they’re listening for is raised which kicks off a task. The object gets enabled (“enabled = true;”), and when it’s got no more tasks to perform it disables itself again.
In fact, using patterns like this, most of my code is dormant most of the time. The only things I have sitting in open game loop code (Update, LateUpdate or FixedUpdate where I’m not using “enabled”) are things that deliberately run logic each tick (user input, AI, other highly time-variant stuff), or dirty little hacks (“I couldn’t be bothered adding events in a bunch of places to detect this one case, I’m just going to check it in Update each tick because it’s quick and easy”).
Nothing special or magical, I meant pretty much what you said. Update always gets called when the MonoBehaviour exists and is enabled, coroutines don’t.
This achieves a pretty much identical result to what I’m getting with coroutines. Coroutines have the added advantage in allowing me to group a bunch of similar on/off functions together in a single Component without having to explicitly check each frame to see which should be running.
I tend to use coroutines when the behaviour is trivial and linear. If the behaviour is not trivial or linear, I’ll use some other pattern to deal with it.
Gotcha. I achieve this in a different way.
I think this is a secret I probably be needin’
In all truth, the problem that I see growing for me is that I’m using Update in one component to do a series of state checks, like:
//FILE DOWNLOAD
if (!isCoroutineRunning && isDataLoaded && isUpdateAvailable && !isError)
{
StartCoroutine(DownloadAssets());
}
Which in itself is not a big deal, but I have several of these as this one ‘manager’ component can have a method invoked from a different ‘manager’ (like a menu system may called to the downloader to check for an update, then it will set the isUpdateAvailable flag to true for if something then clicks ‘download’). That’s just one example.
The Update code block is getting a bit cluttered with these, and I think I need to break it down into something more manageable. I can just see this already starting to get a bit unruly, and i’m pretty certain it breaks some basic programming design principle lol.
Interesting, I actually do start my coroutines in Update because I’ve had problems with media players being launch outside of the Update loop using coroutines.
Kick your Update habit forever with coroutines!
public void Start (){
StartCoroutine (FileDownload());
}
IEnumerator FileDownload () {
while (!isDataLoaded && !isUpdateAvailable && isError) yeild return null;
StartCoroutine(DownloadAssets());
}
You can even chain multiple versions together to run the full sequence
public void Start (){
StartCoroutine (FileDownload());
}
IEnumerator FileDownload () {
while (!isDataLoaded && !isUpdateAvailable && isError) yeild return null;
yield return DownloadAssets();
// Process the assets
}
IEnumerator DownloadAssets (){
yield return new www("...");
}
The National Coroutine Association will not be held responsible for any chains that break mid processing. Or for any debugging headaches using this pattern causes.
I’d rather see that as
yield return StartCoroutine (FileDownload());
yield return StartCoroutine (DownloadAssets());
// etc.
Rather than putting coroutine calls in other coroutines. That way you have an explicit overview of what’s happening in one place. Also why I prefer that pattern over turning off and on a bunch of Updates, which makes it less clear what’s going on.
–Eric
this is interesting!.. I did not know you could chain like that ![]()
This would allow me to put some of these routines into their own components that could then be ‘enabled/disabled’ as needed.
my brain is being re-wired as I type… lol
I saw that btw
and wow, I really REALLY get edgy when I have to debug a coroutine… seems like VSplugin and Unity like to crash sometimes.