Alex Rivera | Logout

How does this function with a "yield" work in detail?

Asked 2010-08-09T09:14:49.663
13

I got this method (inside a Unity C# Script), but I do not understand how the "yield" part actually works.

I know from the MSDN that the function will return an IEnumerator which I could iterate throught, but this code waits 1,5 seconds and does not get iterated because this would mean, the objects created inside were created multiple times. Anyone here who can explain me how this code works?

IEnumerator DestroyShip()
{
    // create new gameobject
    Instantiate(ExplosionPrefab, transform.position, transform.rotation);
    // make current gameobject invisible
    gameObject.renderer.enabled = false;
    // set new position for the current gameobject
    transform.position = new Vector3(0f, transform.position.y, transform.position.z);
    // wait for 1,5 seconds 
    yield return new WaitForSeconds(1.5f);
    // make the current gameobject visible again
    gameObject.renderer.enabled = true;
}
Edit
Report

1 Answer

1

It is better to return IEnumerable rather than IEnumerator as it is more flaxible and easy to use. It is even better to use IEnumerable<T>. Yield return is just syntactic sugar for implementing an iterator block, the compiler generates the relevent code as it is essentially standard boiler plate that can be easily generated programatically. You generally use yield return when you want to make a series of single actions apear to be a collection, e.g.:

public IEnumerable<Thing> GetThings()
{
    yield return GetNextThing();
}
answered 2010-08-09T09:27:03.833

Your Answer