Using IEnumerator and yield to implement a delay

So I am a Java guy who's completely new to C#. In fact, I'm not necessarily even learning C# at the moment. However, I came across something curious that I wanted to get others' thoughts on.

Recently, I was watching a YouTube video about some guy using Unity to create the basics for a game. The scripting language he was using within Unity was C#. Now, at one point, he was wanting to implement a screen fade-in and fade-out feature, and did so in a way that made me cringe. Or at least want to cringe, if you catch my drift.

It was a little bit more complex than this, but in a nutshell, he had the following code:

 

public void doSomething() { // do some stuff // ok, need to fade to black, and wait until done before continuing execution fadeToBlack(); // do some other stuff } public IEnumerator fadeToBlack() { isFading = true; // trigger the actual fading animation in Unity while (isFading) { yield return null; } } 

 

So, assuming I'm understanding this correctly, the fadeToBlack() method will sit and spin around and around in a while loop until the isFading variable changes from true to false (which happens once the animation is complete – sorry, didn't include that code). And each cycle in that loop, it's essentially generating a piece of garbage data (in this case, a null value) and streaming it back to the function caller as part of a collection.

Since the caller doesn't care about the collection, it basically just sits there and waits for this stream of null values to stop, at which point it throws the IEnumerator instance on the floor and continues on its merry way.

Is that correct? Or am I missing something fundamental to C# here? Is this sort of thing commonplace, or part of a known best practice?

I'm just wondering, because to me, this feels pretty janky. I feel like the proper way to handle this would be to implement some sort of asynchronous relationship (callback, messaging, whatever) so that the fadeToBlack method just has to notify some other entity when it's done, rather than wasting time (and clock cycles) generating and streaming back useless data.

Any thoughts?

EDIT: formatting

by dougman82 via /r/csharp

Leave a Reply