Thursday, August 22, 2019

unity - Does `yield return false;` have special meaning in Unity3d C# scripts?



In Unity, we have some special things for coroutines that are additional to normal C#.


for example, we can use


yield return WaitForSeconds(5.f);


to have a coroutine wait 5 seconds before continuing.


What do yield return false; and yield return true; do?



Answer




The only possible yield values the scheduler understands are:



  • Classes derived from YieldInstruction (WaitForSeconds, WaitForEndOfFrame, WaitForFixedUpdate, AssetBundleCreateRequest, AssetBundleRequest and Coroutine


  • a WWW object

  • "any other value" which isn't one of the above.


If "any other value" is yielded (which includes "null" a string value any other basic type such as int, bool, ... or a reference to an arbitrary object which isn't one of the above mentioned) the scheduler will "schedule" the coroutine for the next frame.


- Bunny83 answer: Prominent member on Unity Answers



The WaitForEndOfFrame and others of the like, are just blank functions that tag the YieldInstruction in order to decide what to do in the engine.


The default case seems to be WaitForEndOfFrame. So if you yield return something that doesn't have a special meaning, such as a bool, it is the same as WaitForEndOfFrame.


There doesn't seem to be any official documentation on this behavior.





Update


rutter commented about another special case: yield return null


All of the Unity Coroutines including yield return null, run before the frame renders except for WaitForEndOfFrame. You can find rutter's awesome answer over at Unity Answers explaining this further (nice diagrams included).


No comments:

Post a Comment

Simple past, Present perfect Past perfect

Can you tell me which form of the following sentences is the correct one please? Imagine two friends discussing the gym... I was in a good s...