Unity Tidbit: WaitUntil, WaitWhile

If you’ve been working with Unity for any sort of while you’ve probably used Coroutines before. They’re not exactly the bread and butter of using Unity but they’re like the jam or honey you put immediately after. You’ve probably used a lot of “yield return null” to wait for the next frame before resuming execution? I bet you even have used a “yield return null” loop to check a predicate every frame before continuing. I’ve done it myself. I’ve even written a repeating coroutine helper that uses null to check a predicate before running a given action. Well… stop that. Recently (and by ‘recently’, I mean at least a year) Unity now has two new conditions you can use in coroutines: WaitUntil and WaitWhile and they do exactly what you think they do. Just use any of these two instead of your usual “yield return” and put in a function (even a lambda) that returns a boolean then the coroutine will handle the checking by itself. It’ll check every frame if the predicate is fulfilled and will break if it is or isn’t, respectively. The underlying code this represents is exactly the same like you wrote yourself before but now your code can be a lot more elegant. You’re welcome.


Posted in IT, No Category, Programming and tagged , , , by with comments disabled.