- Home /
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.
Answer by Eric5h5 · Apr 16, 2010 at 02:46 AM
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.
@Sethbeastalan: See the code in the answer for the link I posted.
Answer by easy_da_man · Nov 05, 2012 at 01:34 AM
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
That wouldn't be an issue if the code was
while(true)
{
yield Fire();
}
Note that the question was substantially edited after I answered (should have asked a new question ins$$anonymous$$d), which is why my answer doesn't seem to match the question.
Your answer
Follow this Question
Related Questions
How to implement a delay between each time my gun fires (using coroutines or otherwise)?... 2 Answers
The name 'Joystick' does not denote a valid type ('not found') 2 Answers
How do you delay Application.LoadLevel ? 2 Answers
How to delay a function (how to use WaitForSeconds() and yield) 1 Answer
On Trigger Enter no longer works? long delay to activate 2 Answers