I'm still a newbie on Unity, and I'm a little confused with the use of WaitForSeconds in C#.
So far, i've seen that this function is used as a coroutine, but this means it does not belong to the main thread, does it? I want the call to actually pause the main thread. How do i do that in C#?
I have the code:
Debug.Log("The other stuff should print first");
IEnumerator StopTime(float time)
Debug.Log("Time stopped for: " + time);
yield return new WaitForSeconds(time);
Debug.Log("Time Stop END!");
From this code, i'd expect that nothing in the OnGUI method is to be printed before everything from the StopTime method; however, this is not the case, the call to StopTime is done, and the execution continues to the next line.
Can someone tell me how to actually pause the execution?
The compiler turns an IEnumerator function which yields into an internal class which inherits IEnumerator. This class acts like a state machine, with a method to step through each state (MoveNext), and a method to get the current state (Current). Each time it comes across a yield statement it'll cause another state change, with the object being returned being used as the current object.
Unity's StartCoroutine method takes the returned instance of that class and stores it, calling MoveNext while it hasn't finished, and inspecting Current to see what it needs to do to wait for the next yield, which basically determines how long unity waits until calling MoveNext again
Most of this is documented in the .NET documents regarding IEnumerator / generator functions, unity's StartCoroutine basically tying it together to give a fairly elegant coroutine functionality
Example of what it's doing:
What does yield generate?