Why is the yield keyword used with IEnumerator?

    IEnumerator FireContinuously()
    {
        while(true)
        {
            GameObject laser = Instantiate(laserPrefab, 
                                transform.position, 
                                Quaternion.identity) as GameObject;                                            

            laser.GetComponent<Rigidbody2D>().velocity = new Vector2(0, projectileSpeed);
            yield return new WaitForSeconds(projectileFiringPeriod);
        }

    }

I don’t have a very concrete understanding of how the yield keyword is working with IEnumerator. I know with the yield keyword, the program will move back and forth between the caller and the method that contains this keyword, but how does the return type IEnumerator come into play in this situation?

Hi Tim,

The IEnumerator method is a special method. Maybe the official C# docs help you understand the concept?


See also:

1 Like

This topic was automatically closed 24 hours after the last reply. New replies are no longer allowed.

Privacy & Terms