- Home /
A while type statement in the Update function, Yield?
Alright, what I am trying to do is grab all colliders for 5 secs. My first thought is a while statement, but while's don't yield to the update function. So a while is a no no. I tried yielding at the end of the function if the ending condition wasn't met, but that just postpones the finishing of the function, it does not do so recursively until the condition is met.
So what is the solution? How can I call a function once, pass it time IE: GrabColliders(5), keep the game update going, and have that function repeat until that 5 secs is up. I have the function to grab and process colliders, and how to check the time elapsed etc, but how do I keep the function going, with only 1 call, until the condition is met. I would think it has something to do with calling it recursively? If I try to call the same function from itself however, I get an error?
Any help? And thanks in advance for any advice you can offer! Smile
-Grant
Answer by qJake · Jun 19, 2010 at 11:12 AM
IEnumerator DoSomething(float TimeToDie)
{
float elapsedTime = 0;
while(elapsedTime < TimeToDie)
{
// Perform logic here
elapsedTime += Time.deltaTime;
yield return new WaitForEndOfFrame();
}
}
Just start that coroutine like you normally would, and don't put any logic in there that "blocks" the statement, i.e. something that is processor-intensive, or takes a long time to complete.
Ok, awesome. I thought that'd be the solution and it is. yield;. Now I have another problem, how do you call yield from within a class/object. The compiler gives me no errors, but when I execute the object function, it locks up when yield is called? Is it a namespace problem or something? Any help is greatly appreciated :D
You can only yield from within a coroutine. Don't do it anywhere else. Coroutines have to be started with StartCoroutine(), must have the return type IEnumerator, and must contain one yield return ___;.