Course contentsShow
← Unity Game Development
Lesson 132 of 8282. Scripting and LifecycleFree lesson

Conditional Execution with Custom Yield Instructions

Create complex waiting logic by implementing custom yield instructions that pause execution until a specific game condition becomes true.

In this lesson, you will learn how to create your own "waiting rules" by implementing custom yield instructions that pause a coroutine until a specific game condition is met.

Beyond Standard Waits

So far, you’ve used built-in instructions like WaitForSeconds or WaitForEndOfFrame to pause your coroutines. However, sometimes you don't want to wait for a duration; you want to wait until a specific event happens, like a player reaching a certain health threshold or an object moving into a specific zone.

Instead of writing a bulky while loop inside your coroutine to check this every frame, you can create a class that inherits from CustomYieldInstruction. This allows you to encapsulate the "waiting logic" into a clean, reusable object.

Implementing a Custom Instruction

To create your own instruction, you override the keepWaiting property. As long as keepWaiting returns true, the coroutine remains paused. Once it returns false, the coroutine resumes.

Here is how you would create an instruction that waits until a target object reaches a specific height:

public class WaitForHeight : CustomYieldInstruction
{
    private Transform _target;
    private float _minHeight;

    public WaitForHeight(Transform target, float minHeight)
    {
        _target = target;
        _minHeight = minHeight;
    }

    // While this is true, the coroutine stays paused
    public override bool keepWaiting => _target.position.y < _minHeight;
}

Using Your Custom Instruction

Now, using this in your logic becomes very readable. You simply yield return your new class just like you would with a standard instruction:

IEnumerator MonitorHeight()
{
    Debug.Log("Waiting for object to rise...");
    yield return new WaitForHeight(playerTransform, 10f);
    Debug.Log("Object has reached the required height!");
}

By offloading the condition to a CustomYieldInstruction, your primary coroutine remains clean and focused on the "what" instead of the "how." You are essentially teaching Unity a new command that it can use to manage execution flow based on your game's unique state.

Key Takeaway: Custom yield instructions allow you to simplify complex waiting logic by encapsulating game conditions into reusable objects that automatically handle the execution pause.