“Coroutines instead of Update()”. Has anyone tried this sort of approach?
Basically, it seems that it is possible to write fairly clean code if you launch a control coroutine within OnEnable(), and make it work instead of the usual Update() cycle.
Caveats, though:
Coroutines are killed by OnDisable().
OnEnable() cannot be a coroutine. Start() runs only once, so you can’t use Start() as a coroutine if the object is being enabled/disabled often.
If you create something like Texture, Material or RenderTarget within coroutine, it will leak, because those are not garbage-collected (is there a wrapper for those, maybe?)
I suppose it depends what you’re wanting to do in the loop?
If I want something to happen over a period of time but ultimately end at some point, Coroutines. If you want something to always be happening, don’t see the issue with Update.
Though to be honest if I want something to happen over a set period, I prefer asyc methods with UniTask. I find just being able to await blocks of code to be the cleanest approach.
Counterintuitively, I recently found out that this is not true.
Assuming a coroutine was started via:myMonoBehaviour.StartCoroutine(SomeCoroutine());This will stop the coroutine:myMonoBehaviour.gameObject.SetActive(false);But this will not stop the coroutine:myMonoBehaviour.enabled = false;Note that OnDisable runs in both cases.
Sure. I’ve used coroutines for all sorts of things through out the years. For instance using a coroutine for AI logic or some other thing that updates at some interval that yield instructions were better suited for.
I’ve gotten around this by having my own custom Coroutine class that has various modes that allow me to control when/how it disables/cancels.
/// <summary>
/// Flagging enum to define how a Coroutine should deal with its operating MonoBehaviour is disabled or deactivated.
/// </summary>
[System.Flags()]
public enum RadicalCoroutineDisableMode
{
PlayUntilDestroyed = 0,
/// <summary>
/// The default action from Unity. The routine cancels on deactivate, and plays through disable.
/// </summary>
Default = 1,
/// <summary>
/// The default action from Unity. The routine cancels on deactivate, and plays through disable.
/// </summary>
CancelOnDeactivate = 1,
/// <summary>
/// Cancels on disable, still cancels on Deactivate as well.
/// </summary>
CancelOnDisable = 2,
StopOnDeactivate = 4,
StopOnDisable = 8,
Stops = 12,
Resumes = 16,
PausesOnDeactivate = 20,
PausesOnDisable = 24,
Pauses = 28
}
My custom Coroutine class has several other features that I setup long ago before Unity even had the ‘Coroutine’ class for representing state (you used to only be able to stop by string/ienumerator, this was years ago). It’s evolved over the years. Though now a days I’ve been moving away from it just because of things like ‘async’ now being available.
This isn’t really related to Coroutines. Those will leak regardless of where you create them. It has to do with those classes are wrappers around unmanaged objects. You have to call ‘Destroy’ on them.
I just want to clarify this because if you create new instances of these in Update, or Start, or well… anywhere aside from normal resource loading (like it was already attached to an object in a scene/prefab that you loaded). Then yeah, they’re potential memory leaks if you don’t destroy them correctly.
Do what works for you.
There is nothing wrong with Coroutines.
But if you just need something that does a thing every frame… what really is the point of a Coroutine that yields null constantly when Update can get the job done? I’d only use the Coroutine as Update if my Update would get ridiculously complicated otherwise.
Note there’s an important point that a lot seem to not understand about coroutines. Coroutines themselfs are just generator methods. When executed they create a compiler generated statemachine class which is returned (an object that implements the IEnumerator interface). When you pass it to StartCoroutine you essentially hand over the statemachine to Unity’s coroutine scheduler of the MonoBehaviour you call StartCoroutine on. The crucial part is: the coroutine / method does not have to be run on the same MonoBehaviour. In fact, coroutines do not have to be implemented in a MonoBehaviour at all, you just need one as a coroutine “host”.
If you want to create coroutines which keep running even when the object is deactivated, you can simply run them on a MonoBehaviour singleton that is never destroyed or deactivated.
Though keep in mind that when coroutines use / reference anything from the class they are defined in, the statemachine object is essentially a closure and will keep that object alive. This is also true when the actual object has been destroyed since the managed part of that class will exist until all references to it are gone. That means you can even have a running coroutine that belongs to a dead object as long as you run it on a different (still alive) MonoBehaviour. Though keep in mind that you can not use any Unity related things of dead objects (no GetComponent, no access to “name”, transform, etc…). So since with this approach the coroutine is managed on a seperate object, you have to be careful how you start your coroutine and how you’re ending / stopping it.
I mean sure, go for it if there’s a good reason for it.
The big problem I can see is that if the GameObject gets disabled, you lose all the implicit state of the IEnumerator, so everything you want to survive disables needs to be stored in fields. That reduces the cleanliness of just keeping state-local stuff in the coroutine somewhat.
Unless you’re doing a ton of different waits all around the place, an Update with a state machine and some timers might end up being approximately as readable, and have less overhead.
If it’s a single instance of this running, I find that writing a PlayerLoopSystem is cleaner as there’s no need for the singleton or whatever that runs it.
Well, yes and no ^^. It depends. Of course when you completely stop the coroutine when you disable the associated gameobject, the internal state of the coroutine would of course be lost. However the point was that the coroutine can continue to run, even when the gameobject the coroutine belongs to is deactivated. You can make the coroutine simply wait until the object is active again.
while (!gameObject.activeInHierarchy)
yield return null;
You could also include a safety net to make sure the coroutine is terminated / stopped when the associated object is destroyed
if (this == null)
yield break;
Here you can also decommission any resources you may had allocated at the beginning of the coroutine. I would always recommend to exit a coroutine gracefully from the inside. I would not recommend terminating it from the outside. The reasons are similar to terminating threads from the outside, though coroutines are more predictable in that sense. Though complex statemachine could be in any state, so terminating from the outside could produce unwanted edge cases. So it’s always better to let the coroutine itself finish.
Last time I tried that the coroutine silently died when the object was disabled. As mentioned above, they’re silently killed off when gameObject gets disabled, but they continue to run when only component gets disabled.
I also highly doubt that a lot of peole in this thread don’t understand that it is just a generator.
Well, maybe you missed the key point of my reply. I suggested to run the coroutine on a singleton object that is not deactivated. This avoids any trouble for the actual object containing the coroutine itself.
My point had nothing to do with what Unity could do to make the experience better.
My point is that your statement:
Suggests that it happens because it’s “within a coroutine”. Which the coroutine had nothing to do with.
Do you read like HALF of what people say and then just jump to conclussions?
Because… this was my point.
I said:
I’m saying… use update if you’re just yielding null. Use a coroutine if you need timers, or to wait for other stuff that would be “ridiculously complicated otherwise”.
Referencing back to my first statement of my post:
Now of course your quoting me may have just been a way for you to just state your feelings, rather than contest what you were quoting of me.
But that’s really weird. Why would you quote my statements to just say non-sequiturs and/or repeat yourself?
Combined with how you glossed over what @Bunny83 said, just confuses me as to what your intent is exactly. Are we just having a really awkward conversation about “are coroutines useful?”
There’s an easy answer to that… yes. They are useful.
This post burst onto the scene with so much misinformation and false assertions I don’t even know where to begin, but it looks like others have addressed most of the silliness.
Just keep in mind there is ONE SCRIPTING THREAD IN UNITY AND IT DOES EVERYTHING.
Coroutines are there as a flow control construct and have nothing to do with garbage or leaking or performance. You’re not gonna be sooper-sneeky-cheeki-breeki and find some clever new way to make Unity go faster by using Coroutines. That’s not a thing. Work is work and work has to be done by the one Unity main thread.
Here is some timing diagram help:
Good discussion on Update() vs FixedUpdate() timing:
My intent was to discuss and ask for experience of other people in hopes for that tiny chance of learning something that I do not already know.
And if you’re gonna do this over something this simple:
Then next time I’ll just dump that in General instead.
I have no idea what you’re talking about here.
The order of function execution is defined here: https://docs.unity3d.com/Manual/ExecutionOrder.html
Is there a mention anywhere that coroutines are running in another thread? Or that they’re faster? No.
It is the same thread.
However you are able to perform multi-frame code in a linear fashion, which allow you to keep things in one place, hide variables in scopes, use subroutines and functions easily, where every one of them can also run across multiple-frames, while in Update() method that will result in a clumsily done statemachine with a lot of if/else or you’ll have to start writing decorators. Yes, it is a generator expression, and a generator expression creates an anonymous class/state machine with encapsulates variables within.
So what happens when the state machine stops advancing and is terminated mid-way? Anything it had is going to be released to gc, but because scope-based lifetimes are not a thing, because there’s no SafeHandle for GameObject’s, Materials and Textures, because of that unity-based created resources within coroutine are going to leak.
I didn’t ever write anything about them being “faster”, and instead wrote “cleaner”, so I’m honestly baffled, where the heck did you find this amazing idea you mentioned here:
Because it was about code cleanliness and not speed.