- Home /
Duplicate question : http://answers.unity3d.com/questions/300864/how-to-stop-a-co-routine-in-c-instantly.html
Coroutine Won't Stop Using IEnumerator
See my code below. I don't understand why using the string variant of Start/StopCoroutine makes everything work as expected (drains stamina on key press/hold, stops drain on key release), but when I try to use the IEnumerator version of Start/StopCoroutine the stamina drain begins on key press as expected, and continues on key hold, but also continues on key release and never stops.
Am I missing something?
void Update ()
{
if(Input.GetKeyDown(KeyCode.Keypad0) && transform.GetComponent<Attributes>().stamina >
{
transform.GetComponent<Attributes>().AdjustStamina(-2);
blocking = true;
//StartCoroutine("BlockingDrain");
StartCoroutine(BlockingDrain());
}
if(Input.GetKeyUp(KeyCode.Keypad0))
{
blocking = false;
//StopCoroutine("BlockingDrain");
StopCoroutine(BlockingDrain());
}
}
IEnumerator BlockingDrain ()
{
for (;;)
{
transform.GetComponent<Attributes>().AdjustStamina(-1);
yield return new WaitForSeconds(0.25f);
}
}
Answer by Beks_Omega · Jul 19, 2017 at 08:27 PM
The answer in this question should help ya: http://answers.unity3d.com/questions/300864/how-to-stop-a-co-routine-in-c-instantly.html
Follow this Question
Related Questions
Had difficulties implementing intro to Coroutines from unitypatterns.com. Help? 1 Answer
How to stop a coroutine started in Script A from within Script B 1 Answer
Coroutine only fires once instead of looping until stopped. 2 Answers
Can't get while loop to execute more than once in a coroutine before yielding [Solved] 2 Answers
Does UnityEngine.CustomeYieldInstruction works in a seperate thread? 2 Answers