An Explanation Of When And What To Yield Return?

Good morning everyone,

Following this very interesting lecture, I have a faint notion of when it is appropriate to yield return instead of return and when it should be null.
But can someone please explain properly how we decide that?

Thanks in advance :slight_smile: !

The easiest way to think of it is “are we done yet?”

In a standard coroutine (IEnumerator) where your goal is to do something over a period of time instead of all in the same frame, you might delay with

yield return new WaitForSeconds(.1f); 

In an IEnumerator, you must have at least one yield return statement, and to exit a coroutine early, you would use yield break instead of return.

IEnumerables are a bit different. Since an IEnumerable is a collection, you can yield return an individual element in a collection, or you can return a collection. In the RPG course, we’re just using it for IModifierProviders, so our IEnumerable is

IEnumerable<float> GetAdditiveModifiers()

In this case, we’re checking to see if we have the modifier in the category requested, and if we do, we yield return a single float value.
Now suppose you had a List<float> someFloats and you wished to return all of the elements in the list… Since a List is also an IEnumerable, you could simply return someFloats; and all of the elements would be returned to the collection (and the method would also end).

1 Like

Hello Brian!

Thank you for your answer. I have a better idea of what should be done now.
I was confused when in FadeOut, Sam didn’t “start” the Fade routine, but if I understand correctly, using return Fade() executes it right away.
Hopefully my limited vocabulary conveys my thought accurately haha!

This topic was automatically closed 24 hours after the last reply. New replies are no longer allowed.