How can I use yield in C#

Why C# is lacking Javascript features in Unity.. How can I use the similar coding like below in C#?

print ("Starting " + Time.time);
// Start function WaitAndPrint as a coroutine
yield WaitAndPrint();
print ("Done " + Time.time);

function WaitAndPrint () {
    // suspend execution for 5 seconds
    yield WaitForSeconds (5);
    print ("WaitAndPrint "+ Time.time);
}

when I try to call yield in C#, it always say that feature is not supported in C#..

I suggest reading the documentation, and searching this site, before asking questions. You will find plenty of information and answers. I'll even throw in a hint: "StartCoroutine"

3 Answers

3

This should do it, added a couple comments to describe what's needed:

Debug.Log ("Starting " + Time.time);
// Start function WaitAndPrint as a coroutine
//you need to explicitly tell it to start the coroutine - javascript does this implicitly (most of the time)
yield return StartCoroutine(WaitAndPrint());
Debug.Log ("Done " + Time.time);

//the function return type needs to be IEnumerator (javascript does this implicitly) - you'll need to have using System.Collections; up at the top of your code
IEnumerator WaitAndPrint ()
{
    // suspend execution for 5 seconds
    yield return new WaitForSeconds (5);
    Debug.Log ("WaitAndPrint "+ Time.time);
}

Thank you so very much!

`yield` isn't just for coroutines either.

Try doing this in Javascript.

IEnumerator CardinalDirections()
{
    yield return "North";
    yield return "South";
    yield return "East";
    yield return "West";
}

// another function somewhere
foreach( string direction in CardinalDirections() )
{
    Debug.Log( direction );
}

Works fine in Javascript too if you use the right syntax.

I wrote a tutorial on this a while back. liiiiiink

Cheers

==

You may want to modify the linked article - you keep mentioning coroutines being asynchronous and running parallel, neither of which are true (They're run completely synchronously with the main thread)