Delaying through yield

I have this code:

function Fire()
{
    yield WaitForSeconds(delay);
    Instantiate (bullet, transform.position, transform.rotation);
}

But the yield only performs once, and then they just rain bullets on me (which is not good). How can I make it so that it yields after it fires every time?

Now I'm having the problem that it crashes with this code:

function Start()
{
    while(true)
    {
        Fire();
    }
}

I don't get why it's doing this.

That code does yield every time, but if you're calling it from Update, then a new instance of the function will be called every frame, resulting in many of them running simultaneously. So you either have to not use Update (which I would recommend), or use a different method instead of yield.

Also this has been asked before; see here.

As to the “second” question: I do not know if it has been answered… but I guess it hasn’t been answered in the link from Eric5h5. It is more specific to using while() in Unity methods… but Nubi and consorts might find this useful.

If you are in a while() slope with a condition that never changes, then you will stay in this loop forever. Unity then cannot call other functions because you are actually blocking the Unity engine in your while() loop.

Your

function Start()
{
    while(true)
    {
        Fire();
    }
}

function has a condition that never changes → true is always true. You might say that you are using yield and thus you are not blocking stuff. But Fire() yields back inside the while loop. And since true is still true you are firing again. You have no chance of escaping this while loop without changing your code.

Remember (at least for Unity): It is asynchronuous! That means that for “every step” your CPU takes Unity is updating its internal data. And then renders it. If you calculate the weather for the next two weeks in a while loop, no other functions are called during the time you are calculating the weather. And since this takes a lot of time Unity cannot recompute your nice game graphics and stuff and nothing will happen on screen.

Have a nice day and welcome to Jamaica