Unity – CustomYieldInstruction

      Comments Off on Unity – CustomYieldInstruction

Unity 5.3 provides a very simple way to implement custom yield instructions which is a very nice and clean way to implement custom timing logic without adding a bunch of chained coroutines to you code. I recently had a problem with coroutines that rely on button input. In this example I have a coroutine that is initiated with a button input, and has multiple steps that use the same button to move forward. If the coroutine doesn’t wait for that button up to occur I ended up with a situation where the following steps were all processed immediately due to the way that unity gui uses button down as a button press.

This could be solved with coroutines like so:

However with the CustomYieldInstruction we can solve this in a cleaner way.

The CustomYieldInstruction provides the keepWaiting property. As long as this property returns true a yield statement will wait, and once it’s false the consuming code will be allowed to proceed. The usage looks like any other yield instruction that unity provides us:

Simple, right?