- Home /
How to stop a yield function?
How can I make the yield restart the timmer every time it is executed or how can I stop it?
I´ve got this code:
function Grab () {
if ( canGrab ) {
canGrab = false;
grabbing = true;
//Do stuff
yield WaitForSeconds ( grabDelay );
grabbing = false;
//Do stuff
}
}
When the player jumps canGrab is set to true, when he hits a wall his is held there for grabDelay (approx 2 seconds) this works fine but if the player hits a wall, grabs it and then jumps of it and grabs another one the: yield WaitForSeconds ( grabDelay ) is almost over and the second he grabs the wall the grabDelay reaches 0 and he falls off.
How can I make the yield restart the timmer every time it is executed or how can I stop it?
Any help would be greatly apreciated, thanks!
Answer by thaiscorpion · Jul 23, 2012 at 04:01 PM
I dont think its posible to do what I asked. I ended up making a timer that was reduced in the update function and every time grab() is executed the timer is set to the timeDealy.
I hate to bring up an old post, but if anyone is interested, one way is to cancel the coroutine and the start it again (I made a tutorial on it available here) Hope it helps somebody!
Answer by ScroodgeM · Jul 22, 2012 at 05:26 PM
instead of just start coroutine you can do the following
StopCoroutine("Grab"); StartCoroutine("Grab");
This didnt work the yield would still be counting I dont know why
do you start coroutine using string or still using method without quotes? to stop coroutine this way you should start it by method name in string
Answer by Sener Dude · Apr 11, 2014 at 12:07 PM
Try this hack : If you change "enableYieldFunction" to false before yield start. it will not work.
public class Test : MonoBehaviour {
internal bool enableYieldFunction = true;
void OnTriggerEnter2D(Collider2D col)
{
StartCoroutine(EatFood(col)); // Eat Food
}
IEnumerator EatFood(Collider2D col)
{
yield return new WaitForSeconds(10f); // Wait 10 second
if (enableYieldFunction)
{
// Do your things..
}
}
void Update () {
if (Input.GetButtonDown("Fire1"))
{
enableYieldFunction = false; // Stop Eating Food
}
}
}
Your answer
Follow this Question
Related Questions
Problem with yield waitForSeconds in for loop 0 Answers
Confused about Coroutines 2 Answers
How can I make a variable false for a period of time? 3 Answers
Yield Waitforseconds not working at all 3 Answers