r0128 r0128 - 21 days ago 5
C# Question

C# Unity: Unable to stop Coroutine

Once I call this coroutine I am unable to stop it again and it will just go on forever. I have already tried to call it with a string etc...

this block is in a method that is being called in the update method could that have anything to do with it???

This is my code:

if (currentAmmo < 2 && isColorFading == false) {

StartCoroutine (ColourPulse (ammoCounter, initialColor, 2));
isColorFading = true;

} else if (currentAmmo >= 2 && isColorFading == true) {

StopCoroutine (ColourPulse (ammoCounter, initialColor, 2));
ammoCounter.color = initialColor;
isColorFading = false;
}

Answer

You problem is simple. In few words, you must keep a reference of your coroutine in order to stop it :

private IEnumerator myCoroutine ;

// [...]

if (currentAmmo < 2 && isColorFading == false) {

    myCoroutine = ColourPulse (ammoCounter, initialColor, 2) ;
    StartCoroutine ( myCoroutine ) ;
    isColorFading = true;

} else if (currentAmmo >= 2 && isColorFading == true) {

    StopCoroutine (myCoroutine); 
    ammoCounter.color = initialColor;
    isColorFading = false;
}
Comments