what's an yield keyword

Lets start with, use code tags. They’re similar to spoiler tags, just for code formatting instead:

So your code snippets would be:

void Move(Vector3 dir, float t){
    Vector3 start = transform.position;
    Vector3 end = transform.position + dir;
    var x = 0f;
    isMoving = true;
    while (x < t) {
        x += Time.deltaTime;
        transform.position = Vector3.Lerp (start, end, x);
    }
    isMoving = false;
}
public IEnumerator Move(Vector3 dir, float t){
    Vector3 start = transform.position;
    Vector3 end = transform.position + dir;
    var x = 0f;
    isMoving = true;
    while (x < t) {
        x += Time.deltaTime;
        transform.position = Vector3.Lerp (start, end, x);
        yield return null;
    }
    yield return 0; //<<--- don't yield integers. It means nothing, and it causes boxing which results in unnecessary GC
    isMoving = false;
}

As for the problem.

Unity uses a C# feature called ‘iterator functions’:

Basically you create a function that can be enumerated (with a foreach), and each step of the enumeration is the ‘yield’ line of the iterator function.

Then what Unity does is when this iterator function is passed to the ‘StartCoroutine’ method. Unity will iterate/enumerate over the function once per frame.

This gives an effect of waiting between frames (like an Update call).

Furthermore if you return a YieldInstruction, like WaitForSeconds, you can tell unity to wait even longer than a single frame. Like a few seconds in the case of WaitForSeconds, or until a load completes with WWW.

The reason the first code doesn’t work is that you do all of your operations all immediately, instead of over a succession of frames. Your transform technically is moved bit by bit towards the target position… but because you don’t let the frame pass, the screen never gets redrawn until you’ve completed the whole thing. So you never actually visually see it. It all appears to happen immediately.

1 Like