by rednab · 4y ago · 0 comments
It usually takes people a while to wrap their heads around it and (also hinted at in the article) forgetting to add "yield return" in front of an IEnumerator is a common mistake, but it is an awesome tool to flatten out callback hell or complicated every-frame checks.
They are not older or newer, they belong together. IEnumerable has only one method GetEnumerator() which returns an IEnumerator. If you have an IEnumerator, you can iterate over the sequence once [at a time], if you have an IEnumerable you can obtain as many IEnumerator as you need or want.
Both are supported as return types with yield return, in fact if you use IEnumerable, the generated iterator's implementation will be:
IEnumerator GetEnumerator() => return this;This year I began another RTS prototype, but this time using coroutines instead of state machines for doing procedural animation, AI controllers etc.
It doesn't take that long to learn and once you get how it works it makes development a lot nicer. Just a side note, when using these in Unity make sure to look at More Effective Coroutines (free/paid versions available) on the asset store to make sure you're not unnecessarily allocating memory.
It's still a bit of a miss match though. Delay instructions and waiting for other coroutines are implemented as type unsafe yield return values. Still, a pretty good hack. It ends up with a lot less garbage than async/await.
This is how ValueTask is implemented in newer .NET versions which is a struct, but you can roll your own.
Can you elaborate? I was under the impression that `YieldInstruction` is a well-defined type.
Yielding a final value that isn't a yield instruction is a technique to return a value from a coroutine. You can pull the final return value from the IEnumerator's Current property. Hacks on hacks but it gets the job done.
But seeing how async/await is a thing since like a decade, this is another display of Unity doing things their own way for no good reason.
Cancellation is another gotcha with Tasks. The main way to cancel tasks is to use exceptions as control flow. This causes cancellation to be very expensive. You can still use cancellation tokens and check for IsCancelled and finish your task cooperatively but then you're kind of doing thinks in an non-canononical way.
Unity also hasn't done the work to make cheap unity lifecycle delay calls such as Task wait for end of frame, (although they could). The work arounds are expensive.