- Home /
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"
Answer by Mike 3 · Aug 24, 2010 at 03:24 PM
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); }
Answer by Tetrad · Aug 24, 2010 at 07:11 PM
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 ); }
Answer by equalsequals · Aug 24, 2010 at 03:28 PM
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)
That's this article is also useful for working with CoRoutine..
Your answer
Follow this Question
Related Questions
C# WaitForSeconds doesn't seem to work ?? 2 Answers
Last item not being moved (yield problem) 0 Answers
Why is my delay not working? 2 Answers
INTERNAL COMPILER ERROR 0 Answers